Fix checkstyle issues to enforce it 12/62812/7
authorDavid Suarez <david.suarez.fuentes@gmail.com>
Thu, 7 Sep 2017 09:18:53 +0000 (11:18 +0200)
committerTom Pantelis <tompantelis@gmail.com>
Fri, 8 Sep 2017 01:40:13 +0000 (01:40 +0000)
Fix checkstyle issues to enforce it.

Change-Id: I306255919cdfe43208d7c254f2f6455f4126b92f
Signed-off-by: David Suarez <david.suarez.fuentes@gmail.com>
82 files changed:
opendaylight/config/config-manager/pom.xml
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModulesHolder.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java

index b3d68c0b79fe06e46f2d82160ec37399dd7db6f2..f1483b35c04faa9b20a9d25ee97cc515acfca3d5 100644 (file)
@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
     <groupId>org.opendaylight.controller</groupId>
@@ -22,7 +23,7 @@
       <artifactId>guava</artifactId>
     </dependency>
 
-    <!--Dependencies regardign RuntimeGeneratedMappingService-->
+    <!--Dependencies regarding RuntimeGeneratedMappingService-->
     <dependency>
       <groupId>org.opendaylight.mdsal</groupId>
       <artifactId>mdsal-binding-generator-impl</artifactId>
 
   <build>
     <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
@@ -73,7 +81,7 @@
           <instructions>
             <Bundle-Activator>org.opendaylight.controller.config.manager.impl.osgi.ConfigManagerActivator</Bundle-Activator>
             <Private-Package>org.opendaylight.controller.config.manager.*,
-                            javax.annotation.*,</Private-Package>
+              javax.annotation.*,</Private-Package>
             <Export-Package></Export-Package>
           </instructions>
         </configuration>
index ae78c83754696388198f417acf389e599fbaf28f..eb7fd380cf4489f685e0ec9535eee62e4ff2726d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -27,15 +27,16 @@ public class CommitInfo {
 
     public CommitInfo(final List<DestroyedModule> destroyedFromPreviousTransactions,
             final Map<ModuleIdentifier, ModuleInternalTransactionalInfo> commitMap) {
-        this.destroyedFromPreviousTransactions = Collections
-                .unmodifiableList(destroyedFromPreviousTransactions);
+        this.destroyedFromPreviousTransactions = Collections.unmodifiableList(destroyedFromPreviousTransactions);
         this.commitMap = Collections.unmodifiableMap(commitMap);
     }
 
     /**
-     * Get ordered list of modules that can be closed in the same order, i.e.
-     * first element will be a leaf on which no other module depends, n-th
-     * element can only have dependencies with index smaller than n.
+     * Get ordered list of modules that can be closed in the same order, i.e. first
+     * element will be a leaf on which no other module depends, n-th element can
+     * only have dependencies with index smaller than n.
+     *
+     * @return list of destroyed modules
      */
     public List<DestroyedModule> getDestroyedFromPreviousTransactions() {
         return destroyedFromPreviousTransactions;
index dd6ccde37eb33b600fde44c7f633b26490dae2f8..41e2b5bf60cca73c3882889c148a118807ae3108 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.controller.config.manager.impl;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Maps;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -39,6 +38,7 @@ import org.opendaylight.controller.config.api.ValidationException;
 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
 import org.opendaylight.controller.config.api.jmx.CommitStatus;
 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.ConfigTransactionLookupRegistry.TransactionJMXRegistratorFactory;
 import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
 import org.opendaylight.controller.config.manager.impl.dependencyresolver.ModuleInternalTransactionalInfo;
 import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
@@ -75,22 +75,22 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
     private volatile long versionCounter = 0;
 
     /**
-     * Contains current configuration in form of {moduleName:{instanceName,read
-     * only module}} for copying state to new transaction. Each running module
-     * is present just once, no matter how many interfaces it exposes.
+     * Contains current configuration in form of {moduleName:{instanceName,read only
+     * module}} for copying state to new transaction. Each running module is present
+     * just once, no matter how many interfaces it exposes.
      */
     private final ConfigHolder currentConfig = new ConfigHolder();
 
     /**
      * Will return true unless there was a transaction that succeeded during
-     * validation but failed in second phase of commit. In this case the server
-     * is unstable and its state is undefined.
+     * validation but failed in second phase of commit. In this case the server is
+     * unstable and its state is undefined.
      */
     private volatile boolean isHealthy = true;
 
     /**
-     * Holds Map<transactionName, transactionController> and purges it each time
-     * its content is requested.
+     * Holds the map of transactions and purges it each time its content is
+     * requested.
      */
     private final TransactionsHolder transactionsHolder = new TransactionsHolder();
 
@@ -115,20 +115,18 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
 
     // switched in every 2ndPC
     @GuardedBy("readableSRRegistryLock")
-    private CloseableServiceReferenceReadableRegistry readableSRRegistry =
-            ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
+    private CloseableServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl
+            .createInitialSRLookupRegistry();
 
     // constructor
-    public ConfigRegistryImpl(final ModuleFactoriesResolver resolver,
-                              final MBeanServer configMBeanServer, final BindingContextProvider bindingContextProvider) {
-        this(resolver, configMBeanServer,
-                new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
+    public ConfigRegistryImpl(final ModuleFactoriesResolver resolver, final MBeanServer configMBeanServer,
+            final BindingContextProvider bindingContextProvider) {
+        this(resolver, configMBeanServer, new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
     }
 
     // constructor
-    public ConfigRegistryImpl(final ModuleFactoriesResolver resolver,
-                              final MBeanServer configMBeanServer,
-                              final BaseJMXRegistrator baseJMXRegistrator, final BindingContextProvider bindingContextProvider) {
+    public ConfigRegistryImpl(final ModuleFactoriesResolver resolver, final MBeanServer configMBeanServer,
+            final BaseJMXRegistrator baseJMXRegistrator, final BindingContextProvider bindingContextProvider) {
         this.resolver = resolver;
         this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
         this.configMBeanServer = configMBeanServer;
@@ -141,7 +139,7 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
     }
 
     /**
-     * Create new {@link ConfigTransactionControllerImpl }
+     * Create new {@link ConfigTransactionControllerImpl }.
      */
     @Override
     public ObjectName beginConfig() {
@@ -149,32 +147,45 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
     }
 
     /**
-     * @param blankTransaction true if this transaction is created automatically by
-     *                         org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
+     * It returns true if this transaction is created automatically by
+     * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker.
+     *
+     * @param blankTransaction
+     *            true if this transaction is created automatically by
+     *            org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
+     *
+     * @return object name
      */
     public ObjectName beginConfig(final boolean blankTransaction) {
-        // If we're closed or in the process of closing then all modules are destroyed or being destroyed
-        // so there's no point in trying to acquire the lock and beginning an actual transaction. Also we want
-        // to avoid trying to lock as it may block the shutdown process if there is an outstanding transaction
+        // If we're closed or in the process of closing then all modules are destroyed
+        // or being destroyed
+        // so there's no point in trying to acquire the lock and beginning an actual
+        // transaction. Also we want
+        // to avoid trying to lock as it may block the shutdown process if there is an
+        // outstanding transaction
         // attempting to be committed.
         //
-        // We could throw an exception here to indicate this but that's not part of the original API contract
-        // and callers may not be expecting an unchecked exception. Therefore we return a special transaction
+        // We could throw an exception here to indicate this but that's not part of the
+        // original API contract
+        // and callers may not be expecting an unchecked exception. Therefore we return
+        // a special transaction
         // handle that signifies a "no-op".
-        if(closed.get()) {
+        if (closed.get()) {
             return NOOP_TX_NAME;
         }
 
-        if(blankTransaction) {
+        if (blankTransaction) {
             try {
-                // For a "blank" transaction, we'll try to obtain the config lock but "blank" transactions
-                // are initiated via OSGi events so we don't want to block indefinitely or for a long period
+                // For a "blank" transaction, we'll try to obtain the config lock but "blank"
+                // transactions
+                // are initiated via OSGi events so we don't want to block indefinitely or for a
+                // long period
                 // of time.
-                if(!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
+                if (!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
                     LOG.debug("Timed out trying to obtain configTransactionLock");
                     return NOOP_TX_NAME;
                 }
-            } catch(final InterruptedException e) {
+            } catch (final InterruptedException e) {
                 LOG.debug("Interrupted trying to obtain configTransactionLock", e);
                 Thread.currentThread().interrupt();
                 return NOOP_TX_NAME;
@@ -195,8 +206,8 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         versionCounter++;
         final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
 
-        TransactionJMXRegistratorFactory factory =
-                () -> baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
+        TransactionJMXRegistratorFactory factory = () -> baseJMXRegistrator
+                .createTransactionJMXRegistrator(transactionName);
 
         Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
                 resolver.getAllFactories());
@@ -206,22 +217,21 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
             String name = moduleInternalInfo.getModuleFactory().getImplementationName();
             if (!allCurrentFactories.containsKey(name)) {
                 LOG.trace("Factory {} not found in SR, using reference from previous commit", name);
-                allCurrentFactories.put(name,
-                        Maps.immutableEntry(moduleInternalInfo.getModuleFactory(), moduleInternalInfo.getBundleContext()));
+                allCurrentFactories.put(name, Maps.immutableEntry(moduleInternalInfo.getModuleFactory(),
+                        moduleInternalInfo.getBundleContext()));
             }
         }
         allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);
 
         // closed by transaction controller
-        ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
-                transactionName), factory, allCurrentFactories);
-        SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
-                readableSRRegistry, txLookupRegistry, allCurrentFactories);
+        ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
+                new TransactionIdentifier(transactionName), factory, allCurrentFactories);
+        SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
+                .createSRWritableRegistry(readableSRRegistry, txLookupRegistry, allCurrentFactories);
 
         ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
-                txLookupRegistry, version, bindingContextProvider,
-                versionCounter, allCurrentFactories, transactionsMBeanServer,
-                configMBeanServer, blankTransaction, writableRegistry);
+                txLookupRegistry, version, bindingContextProvider, versionCounter, allCurrentFactories,
+                transactionsMBeanServer, configMBeanServer, blankTransaction, writableRegistry);
         try {
             txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
         } catch (final InstanceAlreadyExistsException e) {
@@ -232,14 +242,10 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         return transactionController;
     }
 
-    /**
-     * {@inheritDoc}
-     * @throws ConflictingVersionException
-     */
     @Override
     public CommitStatus commitConfig(final ObjectName transactionControllerON)
             throws ValidationException, ConflictingVersionException {
-        if(NOOP_TX_NAME.equals(transactionControllerON) || closed.get()) {
+        if (NOOP_TX_NAME.equals(transactionControllerON) || closed.get()) {
             return new CommitStatus(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
         }
 
@@ -254,50 +260,40 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
     @GuardedBy("configTransactionLock")
     private CommitStatus commitConfigSafe(final ObjectName transactionControllerON)
             throws ConflictingVersionException, ValidationException {
-        final String transactionName = ObjectNameUtil
-                .getTransactionName(transactionControllerON);
-        LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
+        final String transactionName = ObjectNameUtil.getTransactionName(transactionControllerON);
+        LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version,
+                versionCounter);
 
         // find ConfigTransactionController
-        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder.getCurrentTransactions();
-        Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry = transactions.get(transactionName);
+        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+                transactionsHolder.getCurrentTransactions();
+        Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry =
+                transactions.get(transactionName);
         if (configTransactionControllerEntry == null) {
-            throw new IllegalArgumentException(String.format(
-                    "Transaction with name '%s' not found", transactionName));
+            throw new IllegalArgumentException(String.format("Transaction with name '%s' not found", transactionName));
         }
         ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
         // check optimistic lock
         if (version != configTransactionController.getParentVersion()) {
             throw new ConflictingVersionException(
-                    String.format(
-                            "Optimistic lock failed. Expected parent version %d, was %d",
-                            version,
+                    String.format("Optimistic lock failed. Expected parent version %d, was %d", version,
                             configTransactionController.getParentVersion()));
         }
         // optimistic lock ok
 
         CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
-        lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
-        // non recoverable from here:
-        try {
-            return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
-            // some libs throw Errors: e.g.
-            // javax.xml.ws.spi.FactoryFinder$ConfigurationError
-        } catch (final Throwable t) {
-            isHealthy = false;
-            LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
-            throw Throwables.propagate(t);
-        }
+        lastListOfFactories = Collections
+                .unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
+        return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
     }
 
     @GuardedBy("configTransactionLock")
     private CommitStatus secondPhaseCommit(final ConfigTransactionControllerInternal configTransactionController,
-                                           final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
+            final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
 
         // close instances which were destroyed by the user, including
         // (hopefully) runtime beans
-        for (DestroyedModule toBeDestroyed : commitInfo
-                .getDestroyedFromPreviousTransactions()) {
+        for (DestroyedModule toBeDestroyed : commitInfo.getDestroyedFromPreviousTransactions()) {
             // closes instance (which should close
             // runtime jmx registrator),
             // also closes osgi registration and ModuleJMXRegistrator
@@ -309,17 +305,16 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         // set RuntimeBeanRegistrators on beans implementing
         // RuntimeBeanRegistratorAwareModule
         Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
-        for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
-                .values()) {
+        for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted().values()) {
             // set runtime jmx registrator if required
             Module module = entry.getProxiedModule();
             RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
 
             if (module instanceof RuntimeBeanRegistratorAwareModule) {
 
-                if(entry.hasOldModule()) {
+                if (entry.hasOldModule()) {
 
-                    if(module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
+                    if (module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
                         runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
                         ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
                     } else {
@@ -333,7 +328,7 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
                 }
             }
             // save it to info so it is accessible afterwards
-            if(runtimeBeanRegistrator != null) {
+            if (runtimeBeanRegistrator != null) {
                 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
             }
         }
@@ -353,15 +348,12 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         int orderingIdx = 0;
         for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
             LOG.trace("Registering {}", moduleIdentifier);
-            ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
-                    .get(moduleIdentifier);
+            ModuleInternalTransactionalInfo entry = commitInfo.getCommitted().get(moduleIdentifier);
             if (entry == null) {
-                throw new NullPointerException("Module not found "
-                        + moduleIdentifier);
+                throw new NullPointerException("Module not found " + moduleIdentifier);
             }
 
-            ObjectName primaryReadOnlyON = ObjectNameUtil
-                    .createReadOnlyModuleON(moduleIdentifier);
+            ObjectName primaryReadOnlyON = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier);
 
             // determine if current instance was recreated or reused or is new
 
@@ -372,8 +364,7 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
             // runtime jmx registration - should be taken care of by module
             // itself
             // instance - is closed only if it was destroyed
-            ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
-                    .createModuleJMXRegistrator();
+            ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator.createModuleJMXRegistrator();
 
             OsgiRegistration osgiRegistration = null;
             AutoCloseable instance = entry.getProxiedModule().getInstance();
@@ -401,9 +392,12 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
                 // close old module jmx registrator
                 oldInternalInfo.getModuleJMXRegistrator().close();
 
-                // We no longer need old internal info. Clear it out, so we do not create a serial leak evidenced
-                // by BUG-4514. The reason is that modules retain their resolver, which retains modules. If we retain
-                // the old module, we would have the complete reconfiguration history held in heap for no good reason.
+                // We no longer need old internal info. Clear it out, so we do not create a
+                // serial leak evidenced
+                // by BUG-4514. The reason is that modules retain their resolver, which retains
+                // modules. If we retain
+                // the old module, we would have the complete reconfiguration history held in
+                // heap for no good reason.
                 entry.clearOldInternalInfo();
             } else {
                 // new instance:
@@ -412,34 +406,32 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
             }
             Module realModule = entry.getRealModule();
 
-            DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
-                    realModule, instance, moduleIdentifier,
-                    registryMBeanServer, configMBeanServer);
+            DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(realModule, instance,
+                    moduleIdentifier, registryMBeanServer, configMBeanServer);
 
             // register to JMX
             try {
                 newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
             } catch (final InstanceAlreadyExistsException e) {
-                throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON,e);
+                throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON, e);
             }
 
             // register services to OSGi
-            Map<ServiceInterfaceAnnotation, String /* service ref name */> annotationMapping = configTransactionController.getWritableRegistry().findServiceInterfaces(moduleIdentifier);
-            BundleContext bc = configTransactionController.getModuleFactoryBundleContext(
-                    entry.getModuleFactory().getImplementationName());
+            Map<ServiceInterfaceAnnotation, String> annotationMapping = configTransactionController
+                    .getWritableRegistry().findServiceInterfaces(moduleIdentifier);
+            BundleContext bc = configTransactionController
+                    .getModuleFactoryBundleContext(entry.getModuleFactory().getImplementationName());
             if (osgiRegistration == null) {
-                osgiRegistration = beanToOsgiServiceManager.registerToOsgi(
-                        newReadableConfigBean.getInstance(), moduleIdentifier, bc, annotationMapping);
+                osgiRegistration = beanToOsgiServiceManager.registerToOsgi(newReadableConfigBean.getInstance(),
+                        moduleIdentifier, bc, annotationMapping);
             } else {
                 osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
             }
 
-            RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
-                    .get(entry.getIdentifier());
-            ModuleInternalInfo newInfo = new ModuleInternalInfo(
-                    entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
-                    runtimeBeanRegistrator, newModuleJMXRegistrator,
-                    orderingIdx, entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
+            RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators.get(entry.getIdentifier());
+            ModuleInternalInfo newInfo = new ModuleInternalInfo(entry.getIdentifier(), newReadableConfigBean,
+                    osgiRegistration, runtimeBeanRegistrator, newModuleJMXRegistrator, orderingIdx,
+                    entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
 
             newConfigEntries.put(realModule, newInfo);
             orderingIdx++;
@@ -450,14 +442,13 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         version = configTransactionController.getVersion();
 
         // switch readable Service Reference Registry
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             readableSRRegistry.close();
             readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
                     configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
         }
 
-        return new CommitStatus(newInstances, reusedInstances,
-                recreatedInstances);
+        return new CommitStatus(newInstances, reusedInstances, recreatedInstances);
     }
 
     /**
@@ -465,44 +456,40 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
      */
     @Override
     public List<ObjectName> getOpenConfigs() {
-        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
-                .getCurrentTransactions();
+        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+                transactionsHolder.getCurrentTransactions();
         List<ObjectName> result = new ArrayList<>(transactions.size());
-        for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
-                .values()) {
+        for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
+            configTransactionControllerEntry : transactions.values()) {
             result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
         }
         return result;
     }
 
     /**
-     * Abort open transactions and unregister read only modules. Since this
-     * class is not responsible for registering itself under
-     * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
-     * here.
+     * Abort open transactions and unregister read only modules. Since this class is
+     * not responsible for registering itself under
+     * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it
+     * will not unregister itself here.
      */
     @Override
     public void close() {
-        if(!closed.compareAndSet(false, true)) {
+        if (!closed.compareAndSet(false, true)) {
             return;
         }
 
         // abort transactions
-        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
-                .getCurrentTransactions();
-        for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
-                .values()) {
-
+        Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+                transactionsHolder.getCurrentTransactions();
+        for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
+            configTransactionControllerEntry : transactions.values()) {
             ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
-            try {
-                configTransactionControllerEntry.getValue().close();
-                configTransactionController.abortConfig();
-            } catch (final RuntimeException e) {
-                LOG.debug("Ignoring exception while aborting {}", configTransactionController, e);
-            }
+            configTransactionControllerEntry.getValue().close();
+            configTransactionController.abortConfig();
         }
 
-        // destroy all live objects one after another in order of the dependency hierarchy, from top to bottom
+        // destroy all live objects one after another in order of the dependency
+        // hierarchy, from top to bottom
         List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
 
         LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
@@ -532,8 +519,7 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
      */
     @Override
     public Set<String> getAvailableModuleNames() {
-        return new HierarchicalConfigMBeanFactoriesHolder(
-                resolver.getAllFactories()).getModuleNames();
+        return new HierarchicalConfigMBeanFactoriesHolder(resolver.getAllFactories()).getModuleNames();
     }
 
     /**
@@ -566,20 +552,18 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
      * {@inheritDoc}
      */
     @Override
-    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
-            throws InstanceNotFoundException {
-        return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
+    public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+        ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName);
+        return baseJMXRegistrator.queryNames(namePattern, null);
     }
 
     /**
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupConfigBeans(final String moduleName,
-                                             final String instanceName) {
-        ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
-                instanceName);
-        return baseJMXRegistrator.queryNames(namePattern, null);
+    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+            throws InstanceNotFoundException {
+        return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
     }
 
     /**
@@ -594,12 +578,10 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
-                                              final String instanceName) {
+    public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
         String finalModuleName = moduleName == null ? "*" : moduleName;
         String finalInstanceName = instanceName == null ? "*" : instanceName;
-        ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
-                finalModuleName, finalInstanceName);
+        ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
         return baseJMXRegistrator.queryNames(namePattern, null);
     }
 
@@ -609,58 +591,61 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
         ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
         String transactionName = ObjectNameUtil.getTransactionName(objectName);
         if (transactionName != null) {
-            throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
+            throw new IllegalArgumentException(
+                    "Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
         }
         // make sure exactly one match is found:
-        LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
+        LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName),
+                ObjectNameUtil.getInstanceName(objectName));
     }
 
     // service reference functionality:
     @Override
     public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
         }
     }
 
     @Override
     public Map<String, Map<String, ObjectName>> getServiceMapping() {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.getServiceMapping();
         }
     }
 
     @Override
     public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
         }
     }
 
     @Override
     public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.lookupServiceInterfaceNames(objectName);
         }
     }
 
     @Override
     public String getServiceInterfaceName(final String namespace, final String localName) {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.getServiceInterfaceName(namespace, localName);
         }
     }
 
     @Override
     public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
-        synchronized(readableSRRegistryLock) {
+        synchronized (readableSRRegistryLock) {
             readableSRRegistry.checkServiceReferenceExists(objectName);
         }
     }
 
     @Override
-    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
-        synchronized(readableSRRegistryLock) {
+    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
+            throws InstanceNotFoundException {
+        synchronized (readableSRRegistryLock) {
             return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
         }
     }
@@ -672,110 +657,103 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe
 
     @Override
     public String toString() {
-        return "ConfigRegistryImpl{" +
-                "versionCounter=" + versionCounter +
-                ", version=" + version +
-                '}';
+        return "ConfigRegistryImpl{" + "versionCounter=" + versionCounter + ", version=" + version + '}';
     }
-}
-
-/**
- * Holds currently running modules
- */
-class ConfigHolder {
-    private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
 
     /**
-     * Add all modules to the internal map. Also add service instance to OSGi
-     * Service Registry.
+     * Inner class holding transactions and purges it each time its content is
+     * requested.
      */
-    public void addAll(final Collection<ModuleInternalInfo> configInfos) {
-        if (!currentConfig.isEmpty()) {
-            throw new IllegalStateException(
-                    "Error - some config entries were not removed: "
-                            + currentConfig);
-        }
-        for (ModuleInternalInfo configInfo : configInfos) {
-            add(configInfo);
+    class TransactionsHolder {
+        /**
+         * This map keeps transaction names and
+         * {@link ConfigTransactionControllerInternal} instances, because platform
+         * MBeanServer transforms mbeans into another representation. Map is cleaned
+         * every time current transactions are requested.
+         */
+        private final ConcurrentMap<String /* transactionName */,
+            Entry<ConfigTransactionControllerInternal,
+            ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
+
+        public void add(final String transactionName, final ConfigTransactionControllerInternal transactionController,
+                final ConfigTransactionLookupRegistry txLookupRegistry) {
+            Object oldValue = transactions.putIfAbsent(transactionName,
+                    Maps.immutableEntry(transactionController, txLookupRegistry));
+            if (oldValue != null) {
+                throw new IllegalStateException("Error: two transactions with same name");
+            }
         }
-    }
 
-    private void add(final ModuleInternalInfo configInfo) {
-        ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
-        if (oldValue != null) {
-            throw new IllegalStateException(
-                    "Cannot overwrite module with same name:"
-                            + configInfo.getIdentifier() + ":" + configInfo);
+        /**
+         * Purges closed transactions from transactions map. Calling this method more
+         * than once within the method can modify the resulting map that was obtained in
+         * previous calls.
+         *
+         * @return current view on transactions map.
+         */
+        public Map<String, Entry<ConfigTransactionControllerInternal,
+            ConfigTransactionLookupRegistry>> getCurrentTransactions() {
+            // first, remove closed transaction
+            for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>>
+                it = transactions.entrySet().iterator(); it.hasNext();) {
+                Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
+                        .next();
+                if (entry.getValue().getKey().isClosed()) {
+                    it.remove();
+                }
+            }
+            return Collections.unmodifiableMap(transactions);
         }
     }
 
     /**
-     * Remove entry from current config.
+     * Inner class that holds currently running modules.
      */
-    public void remove(final ModuleIdentifier name) {
-        ModuleInternalInfo removed = currentConfig.remove(name);
-        if (removed == null) {
-            throw new IllegalStateException(
-                    "Cannot remove from ConfigHolder - name not found:" + name);
+    class ConfigHolder {
+        private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
+
+        /**
+         * Add all modules to the internal map. Also add service instance to OSGi
+         * Service Registry.
+         */
+        public void addAll(final Collection<ModuleInternalInfo> configInfos) {
+            if (!currentConfig.isEmpty()) {
+                throw new IllegalStateException("Error - some config entries were not removed: " + currentConfig);
+            }
+            for (ModuleInternalInfo configInfo : configInfos) {
+                add(configInfo);
+            }
         }
-    }
 
-    public Collection<ModuleInternalInfo> getEntries() {
-        return currentConfig.values();
-    }
-
-    public List<DestroyedModule> getModulesToBeDestroyed() {
-        List<DestroyedModule> result = new ArrayList<>();
-        for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
-            result.add(moduleInternalInfo.toDestroyedModule());
+        private void add(final ModuleInternalInfo configInfo) {
+            ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
+            if (oldValue != null) {
+                throw new IllegalStateException(
+                        "Cannot overwrite module with same name:" + configInfo.getIdentifier() + ":" + configInfo);
+            }
         }
-        Collections.sort(result);
-        return result;
-    }
-
 
-}
-
-/**
- * Holds Map<transactionName, transactionController> and purges it each time its
- * content is requested.
- */
-class TransactionsHolder {
-    /**
-     * This map keeps transaction names and
-     * {@link ConfigTransactionControllerInternal} instances, because platform
-     * MBeanServer transforms mbeans into another representation. Map is cleaned
-     * every time current transactions are requested.
-     */
-    private final ConcurrentMap<String /* transactionName */,
-            Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
+        /**
+         * Remove entry from current config.
+         */
+        public void remove(final ModuleIdentifier name) {
+            ModuleInternalInfo removed = currentConfig.remove(name);
+            if (removed == null) {
+                throw new IllegalStateException("Cannot remove from ConfigHolder - name not found:" + name);
+            }
+        }
 
-    public void add(final String transactionName,
-                    final ConfigTransactionControllerInternal transactionController, final ConfigTransactionLookupRegistry txLookupRegistry) {
-        Object oldValue = transactions.putIfAbsent(transactionName,
-                Maps.immutableEntry(transactionController, txLookupRegistry));
-        if (oldValue != null) {
-            throw new IllegalStateException(
-                    "Error: two transactions with same name");
+        public Collection<ModuleInternalInfo> getEntries() {
+            return currentConfig.values();
         }
-    }
 
-    /**
-     * Purges closed transactions from transactions map. Calling this method more than once within the
-     * method can modify the resulting map that was obtained in previous calls.
-     *
-     * @return current view on transactions map.
-     */
-    public Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> getCurrentTransactions() {
-        // first, remove closed transaction
-        for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>> it = transactions
-                .entrySet().iterator(); it.hasNext(); ) {
-            Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
-                    .next();
-            if (entry.getValue().getKey().isClosed()) {
-                it.remove();
+        public List<DestroyedModule> getModulesToBeDestroyed() {
+            List<DestroyedModule> result = new ArrayList<>();
+            for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
+                result.add(moduleInternalInfo.toDestroyedModule());
             }
+            Collections.sort(result);
+            return result;
         }
-        return Collections.unmodifiableMap(transactions);
     }
 }
index bc8b6a5288379a70aaa04f69040ed9b9df11107c..827646f3347877ccc4e60c7a4bfe2f4bd7283ca4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -14,10 +14,11 @@ import org.opendaylight.controller.config.api.ConfigRegistry;
  */
 public interface ConfigRegistryImplMXBean extends ConfigRegistry {
     /**
-     * @return version of last committed transaction that is now used as base
+     * Get the version of last committed transaction that is now used as base
      *         version. Transactions can only be committed if their parent
      *         version matches this value, that means, transaction must be
      *         started after last one has been committed.
+     * @return version
      */
     long getVersion();
 
index 7a1a74e75f26c4f8839e2b0661e9577f89e35590..25b691fc182325af50807c94f7557c670a624727 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -49,14 +49,11 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * This is a JMX bean representing current transaction. It contains
- * transaction identifier, unique version and parent version for
- * optimistic locking.
+ * This is a JMX bean representing current transaction. It contains transaction
+ * identifier, unique version and parent version for optimistic locking.
  */
-class ConfigTransactionControllerImpl implements
-        ConfigTransactionControllerInternal,
-        ConfigTransactionControllerImplMXBean,
-        Identifiable<TransactionIdentifier> {
+public class ConfigTransactionControllerImpl implements ConfigTransactionControllerInternal,
+        ConfigTransactionControllerImplMXBean, Identifiable<TransactionIdentifier> {
     private static final Logger LOG = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
 
     private final ConfigTransactionLookupRegistry txLookupRegistry;
@@ -75,8 +72,7 @@ class ConfigTransactionControllerImpl implements
      * during validation.
      */
     @GuardedBy("this")
-    private final AtomicBoolean configBeanModificationDisabled = new AtomicBoolean(
-            false);
+    private final AtomicBoolean configBeanModificationDisabled = new AtomicBoolean(false);
     private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(
             configBeanModificationDisabled);
     private final MBeanServer configMBeanServer;
@@ -87,10 +83,10 @@ class ConfigTransactionControllerImpl implements
     private final SearchableServiceReferenceWritableRegistry writableSRRegistry;
 
     public ConfigTransactionControllerImpl(final ConfigTransactionLookupRegistry txLookupRegistry,
-                                           final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion,
-                                           final Map<String, Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories,
-                                           final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer,
-                                           final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry  writableSRRegistry) {
+            final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion,
+            final Map<String, Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories,
+            final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer,
+            final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry writableSRRegistry) {
         this.txLookupRegistry = txLookupRegistry;
         String transactionName = txLookupRegistry.getTransactionIdentifier().getName();
         this.controllerON = ObjectNameUtil.createTransactionControllerON(transactionName);
@@ -108,7 +104,8 @@ class ConfigTransactionControllerImpl implements
     }
 
     @Override
-    public void copyExistingModulesAndProcessFactoryDiff(final Collection<ModuleInternalInfo> existingModules, final List<ModuleFactory> lastListOfFactories) {
+    public void copyExistingModulesAndProcessFactoryDiff(final Collection<ModuleInternalInfo> existingModules,
+            final List<ModuleFactory> lastListOfFactories) {
         // copy old configuration to this server
         for (ModuleInternalInfo oldConfigInfo : existingModules) {
             try {
@@ -145,7 +142,8 @@ class ConfigTransactionControllerImpl implements
             Set<? extends Module> defaultModules = moduleFactory.getDefaultModules(dependencyResolverManager,
                     bundleContext);
             for (Module module : defaultModules) {
-                // ensure default module to be registered to jmx even if its module factory does not use dependencyResolverFactory
+                // ensure default module to be registered to jmx even if its module factory does
+                // not use dependencyResolverFactory
                 DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(module.getIdentifier());
                 final ObjectName objectName;
                 try {
@@ -155,14 +153,16 @@ class ConfigTransactionControllerImpl implements
                 } catch (final InstanceAlreadyExistsException e) {
                     throw new IllegalStateException(e);
                 }
-
                 // register default module as every possible service
-                final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory);
+                final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
+                        .getServiceInterfaceAnnotations(moduleFactory);
                 for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
                     try {
                         saveServiceReference(qname, module.getIdentifier().getInstanceName(), objectName);
                     } catch (final InstanceNotFoundException e) {
-                        throw new IllegalStateException("Unable to register default module instance " + module + " as a service of " + qname, e);
+                        throw new IllegalStateException(
+                                "Unable to register default module instance " + module + " as a service of " + qname,
+                                e);
                     }
                 }
             }
@@ -173,23 +173,26 @@ class ConfigTransactionControllerImpl implements
             List<ModuleIdentifier> modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory);
             for (ModuleIdentifier name : modulesOfRemovedFactory) {
                 // remove service refs
-                final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name).getModuleFactory();
-                final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory);
+                final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name)
+                        .getModuleFactory();
+                final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
+                        .getServiceInterfaceAnnotations(moduleFactory);
                 for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
                     try {
                         removeServiceReference(qname, name.getInstanceName());
                     } catch (final InstanceNotFoundException e) {
-                        throw new IllegalStateException("Unable to UNregister default module instance " + name + " as a service of " + qname, e);
+                        throw new IllegalStateException(
+                                "Unable to UNregister default module instance " + name + " as a service of " + qname,
+                                e);
                     }
                 }
-
                 // close module
                 destroyModule(name);
             }
         }
     }
 
-
+    @SuppressWarnings("IllegalCatch")
     private synchronized void copyExistingModule(final ModuleInternalInfo oldConfigBeanInfo)
             throws InstanceAlreadyExistsException {
 
@@ -211,16 +214,14 @@ class ConfigTransactionControllerImpl implements
         DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(moduleIdentifier);
         try {
 
-            module = moduleFactory.createModule(
-                    moduleIdentifier.getInstanceName(), dependencyResolver,
+            module = moduleFactory.createModule(moduleIdentifier.getInstanceName(), dependencyResolver,
                     oldConfigBeanInfo.getReadableModule(), bc);
         } catch (final Exception e) {
-            throw new IllegalStateException(String.format(
-                    "Error while copying old configuration from %s to %s",
+            throw new IllegalStateException(String.format("Error while copying old configuration from %s to %s",
                     oldConfigBeanInfo, moduleFactory), e);
         }
-        putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module, moduleFactory, oldConfigBeanInfo, dependencyResolver,
-                oldConfigBeanInfo.isDefaultBean(), bc);
+        putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module, moduleFactory, oldConfigBeanInfo,
+                dependencyResolver, oldConfigBeanInfo.isDefaultBean(), bc);
     }
 
     @Override
@@ -237,11 +238,10 @@ class ConfigTransactionControllerImpl implements
 
         DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(moduleIdentifier);
         BundleContext bundleContext = getModuleFactoryBundleContext(moduleFactory.getImplementationName());
-        Module module = moduleFactory.createModule(instanceName, dependencyResolver,
-                bundleContext);
+        Module module = moduleFactory.createModule(instanceName, dependencyResolver, bundleContext);
         boolean defaultBean = false;
-        return putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module,
-                moduleFactory, null, dependencyResolver, defaultBean, bundleContext);
+        return putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module, moduleFactory, null, dependencyResolver,
+                defaultBean, bundleContext);
     }
 
     @Override
@@ -252,43 +252,40 @@ class ConfigTransactionControllerImpl implements
         ObjectNameUtil.checkDomain(objectName);
         ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(objectName, ObjectNameUtil.TYPE_MODULE);
 
-        ModuleInternalTransactionalInfo txInfo = dependencyResolverManager.findModuleInternalTransactionalInfo(moduleIdentifier);
+        ModuleInternalTransactionalInfo txInfo = dependencyResolverManager
+                .findModuleInternalTransactionalInfo(moduleIdentifier);
         Module realModule = txInfo.getRealModule();
-        if(realModule instanceof AbstractModule) {
-            ((AbstractModule<?>)realModule).setCanReuseInstance(false);
+        if (realModule instanceof AbstractModule) {
+            ((AbstractModule<?>) realModule).setCanReuseInstance(false);
         }
     }
 
-    private synchronized ObjectName putConfigBeanToJMXAndInternalMaps(
-            final ModuleIdentifier moduleIdentifier, final Module module,
-            final ModuleFactory moduleFactory,
+    private synchronized ObjectName putConfigBeanToJMXAndInternalMaps(final ModuleIdentifier moduleIdentifier,
+            final Module module, final ModuleFactory moduleFactory,
             @Nullable final ModuleInternalInfo maybeOldConfigBeanInfo, final DependencyResolver dependencyResolver,
-            final boolean isDefaultBean, final BundleContext bundleContext)
-            throws InstanceAlreadyExistsException {
+            final boolean isDefaultBean, final BundleContext bundleContext) throws InstanceAlreadyExistsException {
 
         LOG.debug("Adding module {} to transaction {}", moduleIdentifier, this);
         if (!moduleIdentifier.equals(module.getIdentifier())) {
-            throw new IllegalStateException("Incorrect name reported by module. Expected "
-                    + moduleIdentifier + ", got " + module.getIdentifier());
+            throw new IllegalStateException("Incorrect name reported by module. Expected " + moduleIdentifier + ", got "
+                    + module.getIdentifier());
         }
         if (!dependencyResolver.getIdentifier().equals(moduleIdentifier)) {
             throw new IllegalStateException("Incorrect name reported by dependency resolver. Expected "
                     + moduleIdentifier + ", got " + dependencyResolver.getIdentifier());
         }
-        DynamicMBean writableDynamicWrapper = new DynamicWritableWrapper(
-                module, moduleIdentifier, getTransactionIdentifier().getName(),
-                readOnlyAtomicBoolean, transactionsMBeanServer,
+        DynamicMBean writableDynamicWrapper = new DynamicWritableWrapper(module, moduleIdentifier,
+                getTransactionIdentifier().getName(), readOnlyAtomicBoolean, transactionsMBeanServer,
                 configMBeanServer);
 
-        ObjectName writableON = ObjectNameUtil.createTransactionModuleON(
-                getTransactionIdentifier().getName(), moduleIdentifier);
+        ObjectName writableON = ObjectNameUtil.createTransactionModuleON(getTransactionIdentifier().getName(),
+                moduleIdentifier);
         // put wrapper to jmx
         TransactionModuleJMXRegistration transactionModuleJMXRegistration = getTxModuleJMXRegistrator()
                 .registerMBean(writableDynamicWrapper, writableON);
 
-        dependencyResolverManager.put(
-                moduleIdentifier, module, moduleFactory,
-                maybeOldConfigBeanInfo, transactionModuleJMXRegistration, isDefaultBean, bundleContext);
+        dependencyResolverManager.put(moduleIdentifier, module, moduleFactory, maybeOldConfigBeanInfo,
+                transactionModuleJMXRegistration, isDefaultBean, bundleContext);
         return writableON;
     }
 
@@ -296,27 +293,17 @@ class ConfigTransactionControllerImpl implements
     public synchronized void destroyModule(final ObjectName objectName) throws InstanceNotFoundException {
         checkTransactionName(objectName);
         ObjectNameUtil.checkDomain(objectName);
-        ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(objectName,
-                ObjectNameUtil.TYPE_MODULE);
+        ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(objectName, ObjectNameUtil.TYPE_MODULE);
         destroyModule(moduleIdentifier);
     }
 
-    private void checkTransactionName(final ObjectName objectName) {
-        String foundTransactionName = ObjectNameUtil
-                .getTransactionName(objectName);
-        if (!getTransactionIdentifier().getName().equals(foundTransactionName)) {
-            throw new IllegalArgumentException("Wrong transaction name "
-                    + objectName);
-        }
-    }
-
     private synchronized void destroyModule(final ModuleIdentifier moduleIdentifier) {
         LOG.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
         transactionStatus.checkNotAborted();
 
-        ModuleInternalTransactionalInfo found = dependencyResolverManager.findModuleInternalTransactionalInfo(moduleIdentifier);
-        if (!blankTransaction &&
-                found.isDefaultBean()) {
+        ModuleInternalTransactionalInfo found = dependencyResolverManager
+                .findModuleInternalTransactionalInfo(moduleIdentifier);
+        if (!blankTransaction && found.isDefaultBean()) {
             LOG.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
         }
         // first remove refNames, it checks for objectname existence
@@ -334,6 +321,13 @@ class ConfigTransactionControllerImpl implements
         removedTInfo.getTransactionModuleJMXRegistration().close();
     }
 
+    private void checkTransactionName(final ObjectName objectName) {
+        String foundTransactionName = ObjectNameUtil.getTransactionName(objectName);
+        if (!getTransactionIdentifier().getName().equals(foundTransactionName)) {
+            throw new IllegalArgumentException("Wrong transaction name " + objectName);
+        }
+    }
+
     @Override
     public long getParentVersion() {
         return parentVersion;
@@ -357,27 +351,24 @@ class ConfigTransactionControllerImpl implements
         }
     }
 
+    @SuppressWarnings("IllegalCatch")
     private void validateNoLocks() throws ValidationException {
         transactionStatus.checkNotAborted();
         LOG.trace("Validating transaction {}", getTransactionIdentifier());
         // call validate()
         List<ValidationException> collectedExceptions = new ArrayList<>();
-        for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
-                .getAllModules().entrySet()) {
+        for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager.getAllModules().entrySet()) {
             ModuleIdentifier name = entry.getKey();
             Module module = entry.getValue();
             try {
                 module.validate();
             } catch (final Exception e) {
-                LOG.warn("Validation exception in {}", getTransactionName(),
-                        e);
-                collectedExceptions.add(ValidationException
-                        .createForSingleException(name, e));
+                LOG.warn("Validation exception in {}", getTransactionName(), e);
+                collectedExceptions.add(ValidationException.createForSingleException(name, e));
             }
         }
         if (!collectedExceptions.isEmpty()) {
-            throw ValidationException
-                    .createFromCollectedValidationExceptions(collectedExceptions);
+            throw ValidationException.createFromCollectedValidationExceptions(collectedExceptions);
         }
         LOG.trace("Validated transaction {}", getTransactionIdentifier());
     }
@@ -385,13 +376,12 @@ class ConfigTransactionControllerImpl implements
     /**
      * If this method passes validation, it will grab
      * {@link TransactionStatus#secondPhaseCommitStarted} lock. This lock will
-     * prevent calling @{link #validateBeforeCommitAndLockTransaction},
-     * effectively only allowing to call {@link #secondPhaseCommit} after
-     * successful return of this method.
+     * prevent calling @{link #validateBeforeCommitAndLockTransaction}, effectively
+     * only allowing to call {@link #secondPhaseCommit} after successful return of
+     * this method.
      */
     @Override
-    public synchronized CommitInfo validateBeforeCommitAndLockTransaction()
-            throws ValidationException {
+    public synchronized CommitInfo validateBeforeCommitAndLockTransaction() throws ValidationException {
         transactionStatus.checkNotAborted();
         transactionStatus.checkNotCommitStarted();
         configBeanModificationDisabled.set(true);
@@ -418,34 +408,28 @@ class ConfigTransactionControllerImpl implements
         transactionStatus.checkCommitStarted();
         if (!configBeanModificationDisabled.get()) {
             throw new IllegalStateException(
-                    "Internal error - validateBeforeCommitAndLockTransaction should be called "
-                            + "to obtain a lock");
+                    "Internal error - validateBeforeCommitAndLockTransaction should be called " + "to obtain a lock");
         }
 
         LOG.trace("Committing transaction {}", getTransactionIdentifier());
 
         Map<ModuleIdentifier, Module> allModules = dependencyResolverManager.getAllModules();
 
-        // call getInstance() on all Modules from top to bottom (from source to target of the dependency relation)
-        // The source of a dependency closes itself and calls getInstance recursively on the dependencies (in case of reconfiguration)
-        // This makes close() calls from top to bottom while createInstance() calls are performed bottom to top
-        List<ModuleIdentifier> sortedModuleIdentifiers = Lists.reverse(dependencyResolverManager.getSortedModuleIdentifiers());
+        // call getInstance() on all Modules from top to bottom (from source to target
+        // of the dependency relation)
+        // The source of a dependency closes itself and calls getInstance recursively on
+        // the dependencies (in case of reconfiguration)
+        // This makes close() calls from top to bottom while createInstance() calls are
+        // performed bottom to top
+        List<ModuleIdentifier> sortedModuleIdentifiers = Lists
+                .reverse(dependencyResolverManager.getSortedModuleIdentifiers());
         for (ModuleIdentifier moduleIdentifier : sortedModuleIdentifiers) {
             Module module = allModules.get(moduleIdentifier);
 
-            try {
-                LOG.debug("About to commit {} in transaction {}",
-                        moduleIdentifier, getTransactionIdentifier());
-                AutoCloseable instance = module.getInstance();
-                Preconditions.checkNotNull(instance, "Instance is null:%s in transaction %s", moduleIdentifier, getTransactionIdentifier());
-            } catch (Exception e) {
-                LOG.error("Commit failed on {} in transaction {}", moduleIdentifier,
-                        getTransactionIdentifier(), e);
-                internalAbort();
-                throw new IllegalStateException(
-                        String.format("Error - getInstance() failed for %s in transaction %s",
-                                moduleIdentifier, getTransactionIdentifier()), e);
-            }
+            LOG.debug("About to commit {} in transaction {}", moduleIdentifier, getTransactionIdentifier());
+            AutoCloseable instance = module.getInstance();
+            Preconditions.checkNotNull(instance, "Instance is null:%s in transaction %s", moduleIdentifier,
+                    getTransactionIdentifier());
         }
 
         LOG.trace("Committed configuration {}", getTransactionIdentifier());
@@ -503,17 +487,17 @@ class ConfigTransactionControllerImpl implements
      * {@inheritDoc}
      */
     @Override
-    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
-            throws InstanceNotFoundException {
-        return txLookupRegistry.lookupConfigBean(moduleName, instanceName);
+    public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+        return txLookupRegistry.lookupConfigBeans(moduleName, instanceName);
     }
 
     /**
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
-        return txLookupRegistry.lookupConfigBeans(moduleName, instanceName);
+    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+            throws InstanceNotFoundException {
+        return txLookupRegistry.lookupConfigBean(moduleName, instanceName);
     }
 
     /**
@@ -524,7 +508,6 @@ class ConfigTransactionControllerImpl implements
         txLookupRegistry.checkConfigBeanExists(objectName);
     }
 
-
     /**
      * {@inheritDoc}
      */
@@ -537,8 +520,7 @@ class ConfigTransactionControllerImpl implements
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
-                                              final String instanceName) {
+    public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
         return txLookupRegistry.lookupRuntimeBeans(moduleName, instanceName);
     }
 
@@ -587,7 +569,8 @@ class ConfigTransactionControllerImpl implements
 
     @Override
     public BundleContext getModuleFactoryBundleContext(final String factoryName) {
-        Map.Entry<ModuleFactory, BundleContext> factoryBundleContextEntry = this.currentlyRegisteredFactories.get(factoryName);
+        Map.Entry<ModuleFactory, BundleContext> factoryBundleContextEntry = this.currentlyRegisteredFactories
+                .get(factoryName);
         if (factoryBundleContextEntry == null || factoryBundleContextEntry.getValue() == null) {
             throw new NullPointerException("Bundle context of " + factoryName + " ModuleFactory not found.");
         }
@@ -596,9 +579,9 @@ class ConfigTransactionControllerImpl implements
 
     // service reference functionality:
 
-
     @Override
-    public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
+    public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName,
+            final String refName) {
         return writableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
     }
 
@@ -608,12 +591,14 @@ class ConfigTransactionControllerImpl implements
     }
 
     @Override
-    public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
+    public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(
+            final String serviceInterfaceQName) {
         return writableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
     }
 
     @Override
-    public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
+    public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
+            throws InstanceNotFoundException {
         return writableSRRegistry.lookupServiceInterfaceNames(objectName);
     }
 
@@ -623,12 +608,14 @@ class ConfigTransactionControllerImpl implements
     }
 
     @Override
-    public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON) throws InstanceNotFoundException {
+    public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName,
+            final ObjectName moduleON) throws InstanceNotFoundException {
         return writableSRRegistry.saveServiceReference(serviceInterfaceName, refName, moduleON);
     }
 
     @Override
-    public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException {
+    public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName)
+            throws InstanceNotFoundException {
         writableSRRegistry.removeServiceReference(serviceInterfaceName, refName);
     }
 
@@ -643,7 +630,7 @@ class ConfigTransactionControllerImpl implements
     }
 
     @Override
-    public SearchableServiceReferenceWritableRegistry  getWritableRegistry() {
+    public SearchableServiceReferenceWritableRegistry getWritableRegistry() {
         return writableSRRegistry;
     }
 
@@ -663,7 +650,8 @@ class ConfigTransactionControllerImpl implements
     }
 
     @Override
-    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
+    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
+            throws InstanceNotFoundException {
         return writableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
     }
 }
index b35c1dc7d05585bdf95b306441cbdb4a0f85145e..dd506af74fd007958f24a74227c2cd020bbded09 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -12,17 +12,19 @@ import org.opendaylight.controller.config.api.ConfigTransactionController;
 /**
  * Exposes optimistic locking details about transaction.
  */
-public interface ConfigTransactionControllerImplMXBean extends
-        ConfigTransactionController {
+public interface ConfigTransactionControllerImplMXBean extends ConfigTransactionController {
 
     /**
      * Get version of config registry when this transaction was created.
+     *
+     * @return parent version
      */
     long getParentVersion();
 
     /**
      * Get version of current transaction.
+     *
+     * @return version
      */
     long getVersion();
-
 }
index 11e5bfc63ead7c5fb2852ff2546a973cc9d9ff1b..5b7ecb938c2a771c177dd4e39c925200cb41115e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -19,50 +19,53 @@ import org.osgi.framework.BundleContext;
  * Defines contract between {@link ConfigTransactionControllerImpl} (producer)
  * and {@link ConfigRegistryImpl} (consumer).
  */
-interface ConfigTransactionControllerInternal extends
-        ConfigTransactionControllerImplMXBean, AutoCloseable {
-
-
+interface ConfigTransactionControllerInternal extends ConfigTransactionControllerImplMXBean, AutoCloseable {
 
     /**
-     * 1, Copy already committed modules to current transaction.
-     * 2, Diff: compute added and removed factories from last run, then create new modules using
-     * {@link org.opendaylight.controller.config.spi.ModuleFactory#getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory, BundleContext)}
+     * 1, Copy already committed modules to current transaction. 2, Diff: compute
+     * added and removed factories from last run, then create new modules using
+     * {@link org.opendaylight.controller.config.spi
+     * .ModuleFactory#getDefaultModules(org.opendaylight.controller
+     * .config .api.DependencyResolverFactory, BundleContext)}
      * and remove modules belonging to removed factories.
+     *
+     * @param entries
+     *            entries
+     * @param lastListOfFactories
+     *            list of factories
      */
-    void copyExistingModulesAndProcessFactoryDiff(Collection<ModuleInternalInfo> entries, List<ModuleFactory> lastListOfFactories);
+    void copyExistingModulesAndProcessFactoryDiff(Collection<ModuleInternalInfo> entries,
+            List<ModuleFactory> lastListOfFactories);
 
     /**
-     * Call {@link org.opendaylight.controller.config.spi.Module#validate()} on
-     * all beans in transaction. Lock transaction after successful validation.
-     * This method can be called multiple times if validation fails, but cannot
-     * be called after it did not throw exception.
+     * Call {@link org.opendaylight.controller.config.spi.Module#validate()} on all
+     * beans in transaction. Lock transaction after successful validation. This
+     * method can be called multiple times if validation fails, but cannot be called
+     * after it did not throw exception.
      *
-     * @throws {@link RuntimeException} if validation fails. It is safe to run
-     *         this method in future
-     * @return CommitInfo
+     * @return CommitInfo commit info
      */
-    CommitInfo validateBeforeCommitAndLockTransaction()
-            throws ValidationException;
+    CommitInfo validateBeforeCommitAndLockTransaction() throws ValidationException;
 
     /**
-     * Call {@link org.opendaylight.controller.config.spi.Module#getInstance()}
-     * on all beans in transaction. This method can be only called once.
+     * Call {@link org.opendaylight.controller.config.spi.Module#getInstance()} on
+     * all beans in transaction. This method can be only called once.
      *
-     * @throws {@link RuntimeException} commit fails, indicates bug in config
-     *         bean
-     * @return ordered list of module identifiers that respects dependency
-     *         order.
+     * @return ordered list of module identifiers that respects dependency order
      */
     List<ModuleIdentifier> secondPhaseCommit();
 
     /**
-     * @return ObjectName of this transaction controller
+     * Gets the objectName of this transaction controller.
+     *
+     * @return ObjectName
      */
     ObjectName getControllerObjectName();
 
     /**
-     * @return true iif transaction was committed or aborted.
+     * Check if the transaction was committed or aborted.
+     *
+     * @return result of transaction
      */
     boolean isClosed();
 
@@ -70,7 +73,7 @@ interface ConfigTransactionControllerInternal extends
 
     BundleContext getModuleFactoryBundleContext(String factoryName);
 
-    SearchableServiceReferenceWritableRegistry  getWritableRegistry();
+    SearchableServiceReferenceWritableRegistry getWritableRegistry();
 
     TransactionIdentifier getTransactionIdentifier();
 
index 4780f965104621bc4a8d99520880573c2a1e90ac..f9a5acffad044b448b52eefc857a7b62e39ae96c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -24,17 +24,22 @@ import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.osgi.framework.BundleContext;
 
 /**
- * Responsible for creating TransactionJMXRegistrator, registering transaction and all its beans,
- * lookup of beans, closing of TransactionJMXRegistrator.
+ * Responsible for creating TransactionJMXRegistrator, registering transaction
+ * and all its beans, lookup of beans, closing of TransactionJMXRegistrator.
  */
-class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
+class ConfigTransactionLookupRegistry implements LookupRegistry, Closeable {
     private final TransactionJMXRegistrator transactionJMXRegistrator;
     private final TransactionIdentifier transactionIdentifier;
     private final TransactionModuleJMXRegistrator txModuleJMXRegistrator;
     private final Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories;
 
+    interface TransactionJMXRegistratorFactory {
+        TransactionJMXRegistrator create();
+    }
+
     ConfigTransactionLookupRegistry(final TransactionIdentifier transactionIdentifier,
-                                    final TransactionJMXRegistratorFactory factory, final Map<String, Entry<ModuleFactory, BundleContext>> allCurrentFactories) {
+            final TransactionJMXRegistratorFactory factory,
+            final Map<String, Entry<ModuleFactory, BundleContext>> allCurrentFactories) {
         this.transactionIdentifier = transactionIdentifier;
         this.transactionJMXRegistrator = factory.create();
         this.txModuleJMXRegistrator = transactionJMXRegistrator.createTransactionModuleJMXRegistrator();
@@ -42,11 +47,9 @@ class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
     }
 
     private void checkTransactionName(final ObjectName objectName) {
-        String foundTransactionName = ObjectNameUtil
-                .getTransactionName(objectName);
+        String foundTransactionName = ObjectNameUtil.getTransactionName(objectName);
         if (!transactionIdentifier.getName().equals(foundTransactionName)) {
-            throw new IllegalArgumentException("Wrong transaction name "
-                    + objectName);
+            throw new IllegalArgumentException("Wrong transaction name " + objectName);
         }
     }
 
@@ -70,20 +73,19 @@ class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
      * {@inheritDoc}
      */
     @Override
-    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
-            throws InstanceNotFoundException {
-        return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
+    public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+        ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName,
+                transactionIdentifier.getName());
+        return txModuleJMXRegistrator.queryNames(namePattern, null);
     }
 
     /**
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupConfigBeans(final String moduleName,
-                                             final String instanceName) {
-        ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
-                instanceName, transactionIdentifier.getName());
-        return txModuleJMXRegistrator.queryNames(namePattern, null);
+    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+            throws InstanceNotFoundException {
+        return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
     }
 
     @Override
@@ -92,7 +94,8 @@ class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
         ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
         checkTransactionName(objectName);
         // make sure exactly one match is found:
-        LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
+        LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName),
+                ObjectNameUtil.getInstanceName(objectName));
     }
 
     TransactionIdentifier getTransactionIdentifier() {
@@ -108,7 +111,8 @@ class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
         transactionJMXRegistrator.close();
     }
 
-    public void registerMBean(final ConfigTransactionControllerInternal transactionController, final ObjectName controllerObjectName) throws InstanceAlreadyExistsException {
+    public void registerMBean(final ConfigTransactionControllerInternal transactionController,
+            final ObjectName controllerObjectName) throws InstanceAlreadyExistsException {
         transactionJMXRegistrator.registerMBean(transactionController, controllerObjectName);
     }
 
@@ -129,23 +133,15 @@ class ConfigTransactionLookupRegistry  implements LookupRegistry, Closeable {
      * {@inheritDoc}
      */
     @Override
-    public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
-                                              final String instanceName) {
+    public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
         String finalModuleName = moduleName == null ? "*" : moduleName;
         String finalInstanceName = instanceName == null ? "*" : instanceName;
-        ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
-                finalModuleName, finalInstanceName);
+        ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
         return transactionJMXRegistrator.queryNames(namePattern, null);
     }
 
     @Override
     public String toString() {
-        return "ConfigTransactionLookupRegistry{" +
-                "transactionIdentifier=" + transactionIdentifier +
-                '}';
+        return "ConfigTransactionLookupRegistry{" + "transactionIdentifier=" + transactionIdentifier + '}';
     }
 }
-
-interface TransactionJMXRegistratorFactory {
-    TransactionJMXRegistrator create();
-}
index af58dd2746efe47dc7329ab12f43929545afe8bf..cad98b30f4edd9a3f2689fd43bfa0a6127316103 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -79,7 +79,7 @@ public class DeadlockMonitor implements AutoCloseable {
             ModuleIdentifierWithNanos old = new ModuleIdentifierWithNanos();
             while (!this.isInterrupted()) {
                 ModuleIdentifierWithNanos copy;
-                synchronized(this) {
+                synchronized (this) {
                     copy = new ModuleIdentifierWithNanos(DeadlockMonitor.this.top);
                 }
 
@@ -116,7 +116,7 @@ public class DeadlockMonitor implements AutoCloseable {
         private final long nanoTime;
 
         private ModuleIdentifierWithNanos() {
-            this((ModuleIdentifier)null);
+            this((ModuleIdentifier) null);
         }
 
         private ModuleIdentifierWithNanos(final ModuleIdentifier moduleIdentifier) {
@@ -130,20 +130,21 @@ public class DeadlockMonitor implements AutoCloseable {
         }
 
         @Override
-        public boolean equals(final Object o) {
-            if (this == o) {
+        public boolean equals(final Object object) {
+            if (this == object) {
                 return true;
             }
-            if (o == null || getClass() != o.getClass()) {
+            if (object == null || getClass() != object.getClass()) {
                 return false;
             }
 
-            ModuleIdentifierWithNanos that = (ModuleIdentifierWithNanos) o;
+            ModuleIdentifierWithNanos that = (ModuleIdentifierWithNanos) object;
 
             if (nanoTime != that.nanoTime) {
                 return false;
             }
-            if (moduleIdentifier != null ? !moduleIdentifier.equals(that.moduleIdentifier) : that.moduleIdentifier != null) {
+            if (moduleIdentifier != null ? !moduleIdentifier.equals(that.moduleIdentifier)
+                    : that.moduleIdentifier != null) {
                 return false;
             }
 
@@ -153,15 +154,13 @@ public class DeadlockMonitor implements AutoCloseable {
         @Override
         public int hashCode() {
             int result = moduleIdentifier != null ? moduleIdentifier.hashCode() : 0;
-            result = 31 * result + (int) (nanoTime ^ (nanoTime >>> 32));
+            result = 31 * result + (int) (nanoTime ^ nanoTime >>> 32);
             return result;
         }
 
         @Override
         public String toString() {
-            return "ModuleIdentifierWithNanos{" +
-                    moduleIdentifier +
-                    '}';
+            return "ModuleIdentifierWithNanos{" + moduleIdentifier + '}';
         }
     }
 }
index a64d8c33b865e18337b2433a388bfc0e6fff98a5..fa263bc9330b6d07f2b732771c13c8951a8f1d4a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -21,8 +21,7 @@ import org.osgi.framework.BundleContext;
 /**
  * Provides metadata about Module from controller to registry.
  */
-public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>,
-                Identifiable<ModuleIdentifier>{
+public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>, Identifiable<ModuleIdentifier> {
 
     private final ModuleIdentifier name;
     // this registrator is passed to runtime bean registrator and config
@@ -41,16 +40,14 @@ public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>,
     private final ModuleFactory moduleFactory;
     private final BundleContext bundleContext;
 
-    public ModuleInternalInfo(final ModuleIdentifier name,
-            @Nullable final DynamicReadableWrapper readableModule,
+    public ModuleInternalInfo(final ModuleIdentifier name, @Nullable final DynamicReadableWrapper readableModule,
             final OsgiRegistration osgiRegistration,
             @Nullable final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator,
-            final ModuleJMXRegistrator moduleJMXRegistrator, final int orderingIdx,
-            final boolean isDefaultBean, final ModuleFactory moduleFactory, final BundleContext bundleContext) {
+            final ModuleJMXRegistrator moduleJMXRegistrator, final int orderingIdx, final boolean isDefaultBean,
+            final ModuleFactory moduleFactory, final BundleContext bundleContext) {
 
         if (osgiRegistration == null) {
-            throw new IllegalArgumentException(
-                    "Parameter 'osgiRegistration' is missing");
+            throw new IllegalArgumentException("Parameter 'osgiRegistration' is missing");
         }
         this.readableModule = readableModule;
         this.osgiRegistration = osgiRegistration;
@@ -72,8 +69,9 @@ public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>,
     }
 
     /**
+     * Tells if a running instance exists in the system.
      *
-     * @return iif an running instance exists in the system.
+     * @return is there any running instance in the system.
      */
     public boolean hasReadableModule() {
         return readableModule != null;
@@ -94,22 +92,20 @@ public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>,
 
     /**
      * Get index representing dependency ordering within a transaction.
+     *
+     * @return index
      */
     public int getOrderingIdx() {
         return orderingIdx;
     }
 
-    /**
-     * Compare using orderingIdx
-     */
     @Override
-    public int compareTo(final ModuleInternalInfo o) {
-        return Integer.compare(orderingIdx, o.orderingIdx);
+    public int compareTo(final ModuleInternalInfo moduleInternalInfo) {
+        return Integer.compare(orderingIdx, moduleInternalInfo.orderingIdx);
     }
 
     public DestroyedModule toDestroyedModule() {
-        return new DestroyedModule(getIdentifier(),
-                getReadableModule().getInstance(), getModuleJMXRegistrator(),
+        return new DestroyedModule(getIdentifier(), getReadableModule().getInstance(), getModuleJMXRegistrator(),
                 getOsgiRegistration(), getOrderingIdx(), runtimeBeanRegistrator);
     }
 
index 4c5e391f74ebbd0147f1eedea77fc9c110999dae..288f2ac669c30a68d768318741bf659222cfe057 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -15,12 +15,16 @@ import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnota
 
 public interface SearchableServiceReferenceWritableRegistry extends ServiceReferenceWritableRegistry {
     /**
-     * Return mapping between service ref names and service interface annotation for given
-     * module.
+     * Return mapping between service ref names and service interface annotation for
+     * given module.
      *
-     * @throws java.lang.IllegalArgumentException if any of service qNames is not found
-     * @throws java.lang.NullPointerException     if parameter is null
+     * @param moduleIdentifier module id
+     * @return map
+     * @throws java.lang.IllegalArgumentException
+     *             if any of service qNames is not found
+     * @throws java.lang.NullPointerException
+     *             if parameter is null
      */
-    Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(ModuleIdentifier moduleIdentifier);
-
+    Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
+            ModuleIdentifier moduleIdentifier);
 }
index 2b7e2622ba213847e9ec88544b4cdf19f019bb6b..51cef4d3ea9e834d8beca9b8bcaa7ddbe2cb01d6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -39,29 +39,35 @@ import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
+public class ServiceReferenceRegistryImpl
+        implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
     private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
 
     private final Map<String, ModuleFactory> factories;
     private final Map<String, Set<String>> factoryNamesToQNames;
-    // validator of incoming ObjectNames - throws InstanceNotFoundException if not found either in registry or transaction
+    // validator of incoming ObjectNames - throws InstanceNotFoundException if not
+    // found either in registry or transaction
     private final LookupRegistry lookupRegistry;
     private final ServiceReferenceRegistrator serviceReferenceRegistrator;
     // helper method for getting QName of SI from namespace + local name
-    private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>> namespacesToAnnotations;
+    private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>>
+        namespacesToAnnotations;
     private final Map<String /* service qName */, ServiceInterfaceAnnotation> serviceQNamesToAnnotations;
     // all Service Interface qNames for sanity checking
     private final Set<String /* qName */> allQNames;
-    Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef = new HashMap<>();
-
+    Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef =
+            new HashMap<>();
 
     // actual reference database
     private final Map<ServiceReference, ModuleIdentifier> refNames = new HashMap<>();
     private final boolean writable;
-    private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> mBeans = new HashMap<>();
+    private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
+        managementBeans = new HashMap<>();
 
-    private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories, final LookupRegistry lookupRegistry,
-            final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, final boolean writable) {
+    private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories,
+            final LookupRegistry lookupRegistry,
+            final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory,
+            final boolean writable) {
         this.factories = factories;
         this.writable = writable;
         this.lookupRegistry = lookupRegistry;
@@ -75,27 +81,33 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
         for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
             if (!entry.getKey().equals(entry.getValue().getImplementationName())) {
                 LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
-                throw new IllegalArgumentException("Possible error in code: Mismatch between supplied and actual name of " + entry);
+                throw new IllegalArgumentException(
+                        "Possible error in code: Mismatch between supplied and actual name of " + entry);
             }
-            Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue());
-            Set<String> qNames = InterfacesHelper.getQNames(siAnnotations);
+            Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper
+                    .getServiceInterfaceAnnotations(entry.getValue());
+            Set<String> names = InterfacesHelper.getQNames(siAnnotations);
             allAnnotations.addAll(siAnnotations);
-            allQNameSet.addAll(qNames);
-            modifiableFactoryNamesToQNames.put(entry.getKey(), qNames);
+            allQNameSet.addAll(names);
+            modifiableFactoryNamesToQNames.put(entry.getKey(), names);
         }
         this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames);
         this.allQNames = ImmutableSet.copyOf(allQNameSet);
         // fill namespacesToAnnotations
-        Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> modifiableNamespacesToAnnotations = new HashMap<>();
-        Map<String /* service qName*/, ServiceInterfaceAnnotation> modifiableServiceQNamesToAnnotations = new HashMap<>();
+        Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>>
+            modifiableNamespacesToAnnotations = new HashMap<>();
+        Map<String /* service qName */, ServiceInterfaceAnnotation>
+            modifiableServiceQNamesToAnnotations = new HashMap<>();
         for (ServiceInterfaceAnnotation sia : allAnnotations) {
-            Map<String, ServiceInterfaceAnnotation> ofNamespace =
-                    modifiableNamespacesToAnnotations.computeIfAbsent(sia.namespace(), k -> new HashMap<>());
+            Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations
+                    .computeIfAbsent(sia.namespace(), k -> new HashMap<>());
             if (ofNamespace.containsKey(sia.localName())) {
                 LOG.error(
-                        "Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
+                        "Cannot construct namespacesToAnnotations map, conflict between local names in {},"
+                        + " offending local name: {}, map so far {}",
                         sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
-                throw new IllegalArgumentException("Conflict between local names in " + sia.namespace() + " : " + sia.localName());
+                throw new IllegalArgumentException(
+                        "Conflict between local names in " + sia.namespace() + " : " + sia.localName());
             }
             ofNamespace.put(sia.localName(), sia);
             modifiableServiceQNamesToAnnotations.put(sia.value(), sia);
@@ -106,8 +118,10 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     /**
-     * Static constructor for config registry. Since only transaction can write to this registry, it will
-     * return blank state.
+     * Static constructor for config registry. Since only transaction can write to
+     * this registry, it will return blank state.
+     *
+     * @return service reference registry
      */
     public static CloseableServiceReferenceReadableRegistry createInitialSRLookupRegistry() {
         // since this is initial state, just throw exception:
@@ -128,7 +142,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
             }
 
             @Override
-            public ObjectName lookupConfigBean(final String moduleName, final String instanceName) throws InstanceNotFoundException {
+            public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+                    throws InstanceNotFoundException {
                 throw new UnsupportedOperationException();
             }
 
@@ -157,40 +172,41 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
                 return "initial";
             }
         };
-        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = () -> new ServiceReferenceRegistrator() {
-            @Override
-            public String getNullableTransactionName() {
-                throw new UnsupportedOperationException();
-            }
-
-            @Override
-            public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object, final ObjectName on) throws InstanceAlreadyExistsException {
-                throw new UnsupportedOperationException();
-            }
-
-            @Override
-            public void close() {
 
-            }
-        };
+        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+            () -> new ServiceReferenceRegistrator() {
+                @Override
+                public String getNullableTransactionName() {
+                    throw new UnsupportedOperationException();
+                }
+
+                @Override
+                public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object,
+                         final ObjectName on) throws InstanceAlreadyExistsException {
+                    throw new UnsupportedOperationException();
+                }
+
+                @Override
+                public void close() {
+                }
+            };
         return new ServiceReferenceRegistryImpl(Collections.<String, ModuleFactory>emptyMap(), lookupRegistry,
                 serviceReferenceRegistratorFactory, false);
     }
 
-    /**
-     * Static constructor for transaction controller. Take current state as seen by config registry, allow writing new data.
-     */
-    public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(final ServiceReferenceReadableRegistry oldReadableRegistry,
-                                                    final ConfigTransactionLookupRegistry txLookupRegistry,
-                                                    final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
+    public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(
+            final ServiceReferenceReadableRegistry oldReadableRegistry,
+            final ConfigTransactionLookupRegistry txLookupRegistry,
+            final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
 
         if (txLookupRegistry == null) {
             throw new IllegalArgumentException("txLookupRegistry is null");
         }
         ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry;
         Map<String, ModuleFactory> factories = extractFactoriesMap(currentlyRegisteredFactories);
-        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(
-                txLookupRegistry.getTxModuleJMXRegistrator(), txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
+        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+                new ServiceReferenceTransactionRegistratorFactoryImpl(txLookupRegistry.getTxModuleJMXRegistrator(),
+                        txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
         ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(factories, txLookupRegistry,
                 serviceReferenceRegistratorFactory, true);
         copy(old, newRegistry, txLookupRegistry.getTransactionIdentifier().getName());
@@ -199,28 +215,39 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
 
     /**
      * Copy back state to config registry after commit.
+     *
+     * @param oldWritableRegistry
+     *            old registry
+     * @param lookupRegistry
+     *            lookup registry
+     * @param baseJMXRegistrator
+     *            JMX registrator
+     * @return service reference
      */
-    public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(final ServiceReferenceWritableRegistry oldWritableRegistry,
-                                                                            final LookupRegistry lookupRegistry, final BaseJMXRegistrator baseJMXRegistrator) {
+    public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(
+            final ServiceReferenceWritableRegistry oldWritableRegistry, final LookupRegistry lookupRegistry,
+            final BaseJMXRegistrator baseJMXRegistrator) {
         ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldWritableRegistry;
 
-        // even if factories do change, nothing in the mapping can change between transactions
-        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
+        // even if factories do change, nothing in the mapping can change between
+        // transactions
+        ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+                new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
         ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(old.factories, lookupRegistry,
                 serviceReferenceRegistratorFactory, false);
         copy(old, newRegistry, null);
         return newRegistry;
     }
 
-    /**
-     * Fill refNames and mBeans maps from old instance
-     */
-    private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry, final String nullableDstTransactionName) {
-        for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> refNameEntry : old.mBeans.entrySet()) {
+    private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry,
+            final String nullableDstTransactionName) {
+        for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
+            refNameEntry : old.managementBeans.entrySet()) {
             ObjectName currentImplementation;
             ObjectName currentImplementationSrc = refNameEntry.getValue().getKey().getCurrentImplementation();
             if (nullableDstTransactionName != null) {
-                currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc, nullableDstTransactionName);
+                currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc,
+                        nullableDstTransactionName);
             } else {
                 currentImplementation = ObjectNameUtil.withoutTransactionName(currentImplementationSrc);
             }
@@ -234,7 +261,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
         }
     }
 
-    private static Map<String, ModuleFactory> extractFactoriesMap(final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
+    private static Map<String, ModuleFactory> extractFactoriesMap(
+            final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
         Map<String, ModuleFactory> result = new HashMap<>();
         for (Entry<String, Entry<ModuleFactory, BundleContext>> entry : currentlyRegisteredFactories.entrySet()) {
             result.put(entry.getKey(), entry.getValue().getKey());
@@ -243,8 +271,10 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(final ModuleIdentifier moduleIdentifier) {
-        Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef.get(moduleIdentifier);
+    public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
+            final ModuleIdentifier moduleIdentifier) {
+        Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef
+                .get(moduleIdentifier);
         if (result == null) {
             return Collections.emptyMap();
         }
@@ -252,7 +282,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
+    public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
+            throws InstanceNotFoundException {
         lookupRegistry.checkConfigBeanExists(objectName);
 
         String factoryName = ObjectNameUtil.getFactoryName(objectName);
@@ -283,11 +314,11 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     // reading:
 
     @Override
-    public synchronized Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> getServiceMapping() {
+    public synchronized Map<String, Map<String/* refName */, ObjectName>> getServiceMapping() {
         Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> result = new HashMap<>();
-        for (Entry<ServiceReference, ModuleIdentifier> entry: refNames.entrySet()) {
-            String qName = entry.getKey().getServiceInterfaceQName();
-            Map<String /* refName */, ObjectName> innerMap = result.computeIfAbsent(qName, k -> new HashMap<>());
+        for (Entry<ServiceReference, ModuleIdentifier> entry : refNames.entrySet()) {
+            String name = entry.getKey().getServiceInterfaceQName();
+            Map<String /* refName */, ObjectName> innerMap = result.computeIfAbsent(name, k -> new HashMap<>());
             innerMap.put(entry.getKey().getRefName(), getObjectName(entry.getValue()));
         }
         return result;
@@ -305,7 +336,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
+    public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName,
+            final String refName) {
         ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
         ModuleIdentifier moduleIdentifier = refNames.get(serviceReference);
         if (moduleIdentifier == null) {
@@ -316,7 +348,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
+    public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(
+            final String serviceInterfaceQName) {
         Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
         Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
         if (innerMap == null) {
@@ -327,9 +360,10 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
+    public synchronized ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
+            throws InstanceNotFoundException {
         ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
-        if (!mBeans.containsKey(serviceReference)) {
+        if (!managementBeans.containsKey(serviceReference)) {
             throw new InstanceNotFoundException("Cannot find " + serviceReference);
         }
         return getServiceON(serviceReference);
@@ -339,7 +373,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     public synchronized void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
         String actualTransactionName = ObjectNameUtil.getTransactionName(objectName);
         String expectedTransactionName = serviceReferenceRegistrator.getNullableTransactionName();
-        if (writable && actualTransactionName == null || writable && !actualTransactionName.equals(expectedTransactionName)) {
+        if (writable && actualTransactionName == null
+                || writable && !actualTransactionName.equals(expectedTransactionName)) {
             throw new IllegalArgumentException("Mismatched transaction name in " + objectName);
         }
         String serviceQName = ObjectNameUtil.getServiceQName(objectName);
@@ -359,19 +394,20 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON)  throws InstanceNotFoundException {
+    public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName,
+            final ObjectName moduleON) throws InstanceNotFoundException {
         assertWritable();
         ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
         return saveServiceReference(serviceReference, moduleON);
     }
 
-    private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON)
-            throws InstanceNotFoundException{
+    private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference,
+            final ObjectName moduleON) throws InstanceNotFoundException {
         return saveServiceReference(serviceReference, moduleON, false);
     }
 
-    private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON,
-                                                         final boolean skipChecks) throws InstanceNotFoundException {
+    private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference,
+            final ObjectName moduleON, final boolean skipChecks) throws InstanceNotFoundException {
 
         // make sure it is found
         if (!skipChecks) {
@@ -386,18 +422,23 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
         if (serviceInterfaceQNames == null) {
             LOG.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
                     factoryNamesToQNames, moduleIdentifier);
-            throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + moduleIdentifier.getFactoryName());
+            throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory "
+                    + moduleIdentifier.getFactoryName());
         }
         // supplied serviceInterfaceName must exist in this collection
         if (!serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName())) {
-            LOG.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
-            throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory " + moduleIdentifier.getFactoryName());
+            LOG.error("Cannot find qName {} with factory name {}, found {}",
+                    serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(),
+                    serviceInterfaceQNames);
+            throw new IllegalArgumentException(
+                    "Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory "
+                            + moduleIdentifier.getFactoryName());
         }
 
-
         // create service reference object name, put to mBeans
         ObjectName result = getServiceON(serviceReference);
-        Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry = mBeans.get(serviceReference);
+        Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry =
+                managementBeans.get(serviceReference);
         if (mxBeanEntry == null) {
             // create dummy mx bean
             ServiceReferenceMXBeanImpl dummyMXBean = new ServiceReferenceMXBeanImpl(moduleON);
@@ -407,18 +448,20 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
             } catch (final InstanceAlreadyExistsException e) {
                 throw new IllegalStateException("Possible error in code. Cannot register " + result, e);
             }
-            mBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
+            managementBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
         } else {
             // update
             mxBeanEntry.getKey().setCurrentImplementation(moduleON);
         }
         // save to refNames
         refNames.put(serviceReference, moduleIdentifier);
-        Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations =
-                modulesToServiceRef.computeIfAbsent(moduleIdentifier, k -> new HashMap<>());
+        Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations = modulesToServiceRef
+                .computeIfAbsent(moduleIdentifier, k -> new HashMap<>());
 
-        ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations.get(serviceReference.getServiceInterfaceQName());
-        Preconditions.checkNotNull(annotation, "Possible error in code, cannot find annotation for " + serviceReference);
+        ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations
+                .get(serviceReference.getServiceInterfaceQName());
+        Preconditions.checkNotNull(annotation,
+                "Possible error in code, cannot find annotation for " + serviceReference);
         refNamesToAnnotations.put(annotation, serviceReference.getRefName());
         return result;
     }
@@ -429,28 +472,33 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
                     serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
         }
 
-        return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
+        return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(),
+                serviceReference.getRefName());
     }
 
     @Override
-    public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException{
+    public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName)
+            throws InstanceNotFoundException {
         ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
         removeServiceReference(serviceReference);
     }
 
-    private synchronized void removeServiceReference(final ServiceReference serviceReference) throws InstanceNotFoundException {
+    private synchronized void removeServiceReference(final ServiceReference serviceReference)
+            throws InstanceNotFoundException {
         LOG.debug("Removing service reference {} from {}", serviceReference, this);
         assertWritable();
         // is the qName known?
         if (!allQNames.contains(serviceReference.getServiceInterfaceQName())) {
             LOG.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
-            throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName());
+            throw new IllegalArgumentException(
+                    "Cannot find service interface " + serviceReference.getServiceInterfaceQName());
         }
         ModuleIdentifier removed = refNames.remove(serviceReference);
-        if (removed == null){
+        if (removed == null) {
             throw new InstanceNotFoundException("Cannot find " + serviceReference.getServiceInterfaceQName());
         }
-        Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry = mBeans.remove(serviceReference);
+        Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry =
+                managementBeans.remove(serviceReference);
         if (entry == null) {
             throw new IllegalStateException("Possible code error: cannot remove from mBeans: " + serviceReference);
         }
@@ -460,7 +508,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     @Override
     public synchronized void removeAllServiceReferences() {
         assertWritable();
-        for (ServiceReference serviceReference: mBeans.keySet()) {
+        for (ServiceReference serviceReference : managementBeans.keySet()) {
             try {
                 removeServiceReference(serviceReference);
             } catch (final InstanceNotFoundException e) {
@@ -470,7 +518,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
     }
 
     @Override
-    public synchronized boolean removeServiceReferences(final ObjectName moduleObjectName) throws InstanceNotFoundException {
+    public synchronized boolean removeServiceReferences(final ObjectName moduleObjectName)
+            throws InstanceNotFoundException {
         lookupRegistry.checkConfigBeanExists(moduleObjectName);
         String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
         // check that service interface name exist
@@ -478,22 +527,25 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
         return removeServiceReferences(moduleObjectName, serviceInterfaceQNames);
     }
 
-
-    private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> qNames) throws InstanceNotFoundException {
+    private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> names)
+            throws InstanceNotFoundException {
         ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE);
         assertWritable();
-        Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, qNames);
+        Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names);
         for (ServiceReference sr : serviceReferencesLinkingTo) {
             removeServiceReference(sr);
         }
         return !serviceReferencesLinkingTo.isEmpty();
     }
 
-    private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set<String> serviceInterfaceQNames) {
+    private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName,
+            final Set<String> serviceInterfaceQNames) {
         String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
         if (serviceInterfaceQNames == null) {
-            LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
-            throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + factoryName);
+            LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName,
+                    factoryNamesToQNames, moduleObjectName);
+            throw new IllegalStateException(
+                    "Possible error in code: cannot find annotations of existing factory " + factoryName);
         }
         String instanceName = ObjectNameUtil.getInstanceName(moduleObjectName);
         ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
@@ -508,11 +560,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe
 
     @Override
     public String toString() {
-        return "ServiceReferenceRegistryImpl{" +
-                "lookupRegistry=" + lookupRegistry +
-                "refNames=" + refNames +
-                ", factoryNamesToQNames=" + factoryNamesToQNames +
-                '}';
+        return "ServiceReferenceRegistryImpl{" + "lookupRegistry=" + lookupRegistry + "refNames=" + refNames
+                + ", factoryNamesToQNames=" + factoryNamesToQNames + '}';
     }
 
     @Override
index 5fc5182db39cd1b6f73844a127e12c25cf7e20a0..ac056a85ae399e194522e1f18bdb706e49202746 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -27,15 +27,15 @@ public class TransactionIdentifier implements Identifier {
     }
 
     @Override
-    public boolean equals(final Object o) {
-        if (this == o) {
+    public boolean equals(final Object object) {
+        if (this == object) {
             return true;
         }
-        if (o == null || getClass() != o.getClass()) {
+        if (object == null || getClass() != object.getClass()) {
             return false;
         }
 
-        TransactionIdentifier that = (TransactionIdentifier) o;
+        TransactionIdentifier that = (TransactionIdentifier) object;
 
         if (name != null ? !name.equals(that.name) : that.name != null) {
             return false;
index 8fa7fdfddef8b61922bf71accc0327ccc616bfe1..e69aa8611af7f7aff96b543159a48b85b74e87c2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -41,8 +41,7 @@ import org.slf4j.LoggerFactory;
  * by creating proxy that would throw exception if those methods are called
  * during validation. Tracks dependencies for ordering purposes.
  */
-final class DependencyResolverImpl implements DependencyResolver,
-        Comparable<DependencyResolverImpl> {
+public final class DependencyResolverImpl implements DependencyResolver, Comparable<DependencyResolverImpl> {
     private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
 
     private final ModulesHolder modulesHolder;
@@ -53,77 +52,65 @@ final class DependencyResolverImpl implements DependencyResolver,
     private final ServiceReferenceReadableRegistry readableRegistry;
     private final BindingContextProvider bindingContextProvider;
     private final String transactionName;
-    private final MBeanServer mBeanServer;
+    private final MBeanServer beanServer;
     private Integer maxDependencyDepth;
 
-    DependencyResolverImpl(final ModuleIdentifier currentModule,
-                           final TransactionStatus transactionStatus, final ModulesHolder modulesHolder,
-                           final ServiceReferenceReadableRegistry readableRegistry, final BindingContextProvider bindingContextProvider,
-                           final String transactionName, final MBeanServer mBeanServer) {
+    public DependencyResolverImpl(final ModuleIdentifier currentModule, final TransactionStatus transactionStatus,
+            final ModulesHolder modulesHolder, final ServiceReferenceReadableRegistry readableRegistry,
+            final BindingContextProvider bindingContextProvider, final String transactionName,
+            final MBeanServer beanServer) {
         this.bindingContextProvider = bindingContextProvider;
         this.name = currentModule;
         this.transactionStatus = transactionStatus;
         this.modulesHolder = modulesHolder;
         this.readableRegistry = readableRegistry;
         this.transactionName = transactionName;
-        this.mBeanServer = mBeanServer;
+        this.beanServer = beanServer;
     }
 
     /**
      * {@inheritDoc}
      */
-    //TODO: check for cycles
+    // TODO: check for cycles
     @Override
-    public void validateDependency(
-            final Class<? extends AbstractServiceInterface> expectedServiceInterface,
+    public void validateDependency(final Class<? extends AbstractServiceInterface> expectedServiceInterface,
             final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
 
         this.transactionStatus.checkNotCommitted();
         if (expectedServiceInterface == null) {
-            throw new NullPointerException(
-                    "Parameter 'expectedServiceInterface' is null");
+            throw new NullPointerException("Parameter 'expectedServiceInterface' is null");
         }
         if (jmxAttribute == null) {
             throw new NullPointerException("Parameter 'jmxAttribute' is null");
         }
 
         JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
-                "is null, expected dependency implementing "
-                        + expectedServiceInterface, jmxAttribute
-        );
-
+                "is null, expected dependency implementing " + expectedServiceInterface, jmxAttribute);
 
         // check that objectName belongs to this transaction - this should be
         // stripped
         // in DynamicWritableWrapper
-        final boolean hasTransaction = ObjectNameUtil
-                .getTransactionName(dependentReadOnlyON) != null;
-        JmxAttributeValidationException.checkCondition(
-                !hasTransaction,
-                String.format("ObjectName should not contain "
-                                + "transaction name. %s set to %s. ", jmxAttribute,
-                        dependentReadOnlyON
-            ), jmxAttribute
-        );
+        final boolean hasTransaction = ObjectNameUtil.getTransactionName(dependentReadOnlyON) != null;
+        JmxAttributeValidationException.checkCondition(!hasTransaction,
+                String.format("ObjectName should not contain " + "transaction name. %s set to %s. ", jmxAttribute,
+                        dependentReadOnlyON),
+                jmxAttribute);
 
         final ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
 
-        final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON, ObjectNameUtil
-                .TYPE_MODULE);
+        final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON,
+                ObjectNameUtil.TYPE_MODULE);
 
         final ModuleFactory foundFactory = this.modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
 
-        final boolean implementsSI = foundFactory
-                .isModuleImplementingServiceInterface(expectedServiceInterface);
+        final boolean implementsSI = foundFactory.isModuleImplementingServiceInterface(expectedServiceInterface);
         if (!implementsSI) {
             final String message = String.format(
                     "Found module factory does not expose expected service interface. "
                             + "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
                             + "attribute %s",
-                    foundFactory.getImplementationName(), foundFactory,
-                    expectedServiceInterface, newDependentReadOnlyON,
-                    jmxAttribute
-            );
+                    foundFactory.getImplementationName(), foundFactory, expectedServiceInterface,
+                    newDependentReadOnlyON, jmxAttribute);
             throw new JmxAttributeValidationException(message, jmxAttribute);
         }
         synchronized (this) {
@@ -137,16 +124,17 @@ final class DependencyResolverImpl implements DependencyResolver,
         if (ObjectNameUtil.isServiceReference(translatedDependentReadOnlyON)) {
             final String serviceQName = ObjectNameUtil.getServiceQName(translatedDependentReadOnlyON);
             final String refName = ObjectNameUtil.getReferenceName(translatedDependentReadOnlyON);
-            translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
+            // strip again of transaction name
+            translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName(
                     this.readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
         }
         return translatedDependentReadOnlyON;
     }
 
-    //TODO: check for cycles
+    // TODO: check for cycles
     @Override
     public <T> T resolveInstance(final Class<T> expectedType, final ObjectName dependentReadOnlyON,
-                                 final JmxAttribute jmxAttribute) {
+            final JmxAttribute jmxAttribute) {
         final Module module = resolveModuleInstance(dependentReadOnlyON, jmxAttribute);
 
         synchronized (this) {
@@ -155,30 +143,29 @@ final class DependencyResolverImpl implements DependencyResolver,
         final AutoCloseable instance = module.getInstance();
         if (instance == null) {
             final String message = String.format(
-                "Error while %s resolving instance %s. getInstance() returned null. Expected type %s, attribute %s",
-                this.name, module.getIdentifier(), expectedType, jmxAttribute);
+                    "Error while %s resolving instance %s. getInstance() returned null. Expected type %s, attribute %s",
+                    this.name, module.getIdentifier(), expectedType, jmxAttribute);
             throw new JmxAttributeValidationException(message, jmxAttribute);
         }
         try {
             return expectedType.cast(instance);
         } catch (final ClassCastException e) {
             final String message = String.format(
-                "Instance cannot be cast to expected type. Instance class is %s, expected type %s , attribute %s",
-                instance.getClass(), expectedType, jmxAttribute);
+                    "Instance cannot be cast to expected type. Instance class is %s, expected type %s , attribute %s",
+                    instance.getClass(), expectedType, jmxAttribute);
             throw new JmxAttributeValidationException(message, e, jmxAttribute);
         }
     }
 
-    private Module resolveModuleInstance(final ObjectName dependentReadOnlyON,
-                                 final JmxAttribute jmxAttribute) {
-        Preconditions.checkArgument(dependentReadOnlyON != null ,"dependentReadOnlyON");
+    private Module resolveModuleInstance(final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
+        Preconditions.checkArgument(dependentReadOnlyON != null, "dependentReadOnlyON");
         Preconditions.checkArgument(jmxAttribute != null, "jmxAttribute");
         final ObjectName translatedDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
         this.transactionStatus.checkCommitStarted();
         this.transactionStatus.checkNotCommitted();
 
-        final ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(
-                translatedDependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
+        final ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(translatedDependentReadOnlyON,
+                ObjectNameUtil.TYPE_MODULE);
 
         return Preconditions.checkNotNull(this.modulesHolder.findModule(dependentModuleIdentifier, jmxAttribute));
     }
@@ -194,7 +181,8 @@ final class DependencyResolverImpl implements DependencyResolver,
                 .findModuleInternalTransactionalInfo(identifier);
 
         if (moduleInternalTransactionalInfo.hasOldModule()) {
-            final Module oldModule = moduleInternalTransactionalInfo.getOldInternalInfo().getReadableModule().getModule();
+            final Module oldModule = moduleInternalTransactionalInfo.getOldInternalInfo().getReadableModule()
+                    .getModule();
             return currentModule.canReuse(oldModule);
         }
         return false;
@@ -204,7 +192,7 @@ final class DependencyResolverImpl implements DependencyResolver,
     public <T extends BaseIdentity> Class<? extends T> resolveIdentity(final IdentityAttributeRef identityRef,
             final Class<T> expectedBaseClass) {
         final QName qName = QName.create(identityRef.getqNameOfIdentity());
-        final Class<?> deserialized  = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
+        final Class<?> deserialized = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
         if (deserialized == null) {
             throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
                     + this.bindingContextProvider.getBindingContext());
@@ -213,25 +201,21 @@ final class DependencyResolverImpl implements DependencyResolver,
             return (Class<T>) deserialized;
         }
         LOG.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.", identityRef,
-            deserialized, expectedBaseClass);
-        throw new IllegalArgumentException("Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
+                deserialized, expectedBaseClass);
+        throw new IllegalArgumentException(
+                "Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
     }
 
     @Override
     public <T extends BaseIdentity> void validateIdentity(final IdentityAttributeRef identityRef,
             final Class<T> expectedBaseClass, final JmxAttribute jmxAttribute) {
-        try {
-            resolveIdentity(identityRef, expectedBaseClass);
-        } catch (final Exception e) {
-            throw JmxAttributeValidationException.wrap(e, jmxAttribute);
-        }
+        resolveIdentity(identityRef, expectedBaseClass);
     }
 
     @Override
-    public int compareTo(final DependencyResolverImpl o) {
+    public int compareTo(final DependencyResolverImpl dependencyResolverImpl) {
         this.transactionStatus.checkCommitStarted();
-        return Integer.compare(getMaxDependencyDepth(),
-                o.getMaxDependencyDepth());
+        return Integer.compare(getMaxDependencyDepth(), dependencyResolverImpl.getMaxDependencyDepth());
     }
 
     int getMaxDependencyDepth() {
@@ -243,37 +227,35 @@ final class DependencyResolverImpl implements DependencyResolver,
 
     void countMaxDependencyDepth(final DependencyResolverManager manager) {
         // We can calculate the dependency after second phase commit was started
-        // Second phase commit starts after validation and validation adds the dependencies into the dependency resolver, which are necessary for the calculation
-        // FIXME generated code for abstract module declares validate method as non-final
-        // Overriding the validate would cause recreate every time instead of reuse + also possibly wrong close order if there is another module depending
+        // Second phase commit starts after validation and validation adds the
+        // dependencies into the dependency resolver, which are necessary for the
+        // calculation
+        // FIXME generated code for abstract module declares validate method as
+        // non-final
+        // Overriding the validate would cause recreate every time instead of reuse +
+        // also possibly wrong close order if there is another module depending
         this.transactionStatus.checkCommitStarted();
         if (this.maxDependencyDepth == null) {
-            this.maxDependencyDepth = getMaxDepth(this, manager,
-                    new LinkedHashSet<>());
+            this.maxDependencyDepth = getMaxDepth(this, manager, new LinkedHashSet<>());
         }
     }
 
-    private static int getMaxDepth(final DependencyResolverImpl impl,
-                                   final DependencyResolverManager manager,
-                                   final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
+    private static int getMaxDepth(final DependencyResolverImpl impl, final DependencyResolverManager manager,
+            final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
         int maxDepth = 0;
-        final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(
-                chainForDetectingCycles);
+        final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(chainForDetectingCycles);
         chainForDetectingCycles2.add(impl.getIdentifier());
         for (final ModuleIdentifier dependencyName : impl.dependencies) {
-            final DependencyResolverImpl dependentDRI = manager
-                    .getOrCreate(dependencyName);
+            final DependencyResolverImpl dependentDRI = manager.getOrCreate(dependencyName);
             if (chainForDetectingCycles2.contains(dependencyName)) {
-                throw new IllegalStateException(String.format(
-                        "Cycle detected, %s contains %s",
-                        chainForDetectingCycles2, dependencyName));
+                throw new IllegalStateException(
+                        String.format("Cycle detected, %s contains %s", chainForDetectingCycles2, dependencyName));
             }
             int subDepth;
             if (dependentDRI.maxDependencyDepth != null) {
                 subDepth = dependentDRI.maxDependencyDepth;
             } else {
-                subDepth = getMaxDepth(dependentDRI, manager,
-                        chainForDetectingCycles2);
+                subDepth = getMaxDepth(dependentDRI, manager, chainForDetectingCycles2);
                 dependentDRI.maxDependencyDepth = subDepth;
             }
             if (subDepth + 1 > maxDepth) {
@@ -295,7 +277,7 @@ final class DependencyResolverImpl implements DependencyResolver,
         ObjectName newName = translateServiceRefIfPossible(name);
         // add transaction name
         newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
-        return this.mBeanServer.getAttribute(newName, attribute);
+        return this.beanServer.getAttribute(newName, attribute);
     }
 
     @Override
@@ -303,6 +285,6 @@ final class DependencyResolverImpl implements DependencyResolver,
         ObjectName newName = translateServiceRefIfPossible(name);
         // add transaction name
         newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
-        return JMX.newMXBeanProxy(this.mBeanServer, newName, interfaceClass);
+        return JMX.newMXBeanProxy(this.beanServer, newName, interfaceClass);
     }
 }
index ef4aaddf358cc92e40c47bc5883594728ab3793d..ada8a17532a60d879332012bbcffd0d1f0eacbdf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -44,26 +44,26 @@ import org.osgi.framework.BundleContext;
  */
 public class DependencyResolverManager implements DependencyResolverFactory, AutoCloseable {
     @GuardedBy("this")
-    private final Map<ModuleIdentifier, DependencyResolverImpl> moduleIdentifiersToDependencyResolverMap = new HashMap<>();
+    private final Map<ModuleIdentifier, DependencyResolverImpl>
+        moduleIdentifiersToDependencyResolverMap = new HashMap<>();
     private final TransactionIdentifier transactionIdentifier;
     private final ModulesHolder modulesHolder;
     private final TransactionStatus transactionStatus;
     private final ServiceReferenceReadableRegistry readableRegistry;
     private final BindingContextProvider bindingContextProvider;
     private final DeadlockMonitor deadlockMonitor;
-    private final MBeanServer mBeanServer;
+    private final MBeanServer beanServer;
 
     public DependencyResolverManager(final TransactionIdentifier transactionIdentifier,
-                                     final TransactionStatus transactionStatus,
-                                     final ServiceReferenceReadableRegistry readableRegistry, final BindingContextProvider bindingContextProvider,
-                                     final MBeanServer mBeanServer) {
+            final TransactionStatus transactionStatus, final ServiceReferenceReadableRegistry readableRegistry,
+            final BindingContextProvider bindingContextProvider, final MBeanServer beanServer) {
         this.transactionIdentifier = transactionIdentifier;
         this.modulesHolder = new ModulesHolder(transactionIdentifier);
         this.transactionStatus = transactionStatus;
         this.readableRegistry = readableRegistry;
         this.bindingContextProvider = bindingContextProvider;
         this.deadlockMonitor = new DeadlockMonitor(transactionIdentifier);
-        this.mBeanServer = mBeanServer;
+        this.beanServer = beanServer;
     }
 
     @Override
@@ -76,7 +76,7 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         if (dependencyResolver == null) {
             transactionStatus.checkNotCommitted();
             dependencyResolver = new DependencyResolverImpl(name, transactionStatus, modulesHolder, readableRegistry,
-                    bindingContextProvider, transactionIdentifier.getName(), mBeanServer);
+                    bindingContextProvider, transactionIdentifier.getName(), beanServer);
             moduleIdentifiersToDependencyResolverMap.put(name, dependencyResolver);
         }
         return dependencyResolver;
@@ -84,12 +84,11 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
 
     /**
      * Get all dependency resolvers, including those that belong to destroyed
-     * things?
+     * things?.
      */
     private List<DependencyResolverImpl> getAllSorted() {
         transactionStatus.checkCommitStarted();
-        List<DependencyResolverImpl> sorted = new ArrayList<>(
-                moduleIdentifiersToDependencyResolverMap.values());
+        List<DependencyResolverImpl> sorted = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.values());
         for (DependencyResolverImpl dri : sorted) {
             dri.countMaxDependencyDepth(this);
         }
@@ -98,8 +97,7 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
     }
 
     public List<ModuleIdentifier> getSortedModuleIdentifiers() {
-        List<ModuleIdentifier> result = new ArrayList<>(
-                moduleIdentifiersToDependencyResolverMap.size());
+        List<ModuleIdentifier> result = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.size());
         for (DependencyResolverImpl dri : getAllSorted()) {
             ModuleIdentifier driName = dri.getIdentifier();
             result.add(driName);
@@ -107,11 +105,9 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         return result;
     }
 
-    public ModuleInternalTransactionalInfo destroyModule(
-            final ModuleIdentifier moduleIdentifier) {
+    public ModuleInternalTransactionalInfo destroyModule(final ModuleIdentifier moduleIdentifier) {
         transactionStatus.checkNotCommitted();
-        ModuleInternalTransactionalInfo found = modulesHolder
-                .destroyModule(moduleIdentifier);
+        ModuleInternalTransactionalInfo found = modulesHolder.destroyModule(moduleIdentifier);
         moduleIdentifiersToDependencyResolverMap.remove(moduleIdentifier);
         return found;
     }
@@ -123,18 +119,21 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         private final ModuleIdentifier moduleIdentifier;
         private final Module module;
 
-        // optimization: subsequent calls to getInstance MUST return the same value during transaction,
+        // optimization: subsequent calls to getInstance MUST return the same value
+        // during transaction,
         // so it is safe to cache the response
         private Object cachedInstance;
 
-        ModuleInvocationHandler(final DeadlockMonitor deadlockMonitor, final ModuleIdentifier moduleIdentifier, final Module module) {
+        ModuleInvocationHandler(final DeadlockMonitor deadlockMonitor, final ModuleIdentifier moduleIdentifier,
+                final Module module) {
             this.deadlockMonitor = Preconditions.checkNotNull(deadlockMonitor);
             this.moduleIdentifier = Preconditions.checkNotNull(moduleIdentifier);
             this.module = Preconditions.checkNotNull(module);
         }
 
         @Override
-        protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
+        protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
+                throws Throwable {
             boolean isGetInstance = "getInstance".equals(method.getName());
             if (isGetInstance) {
                 if (cachedInstance != null) {
@@ -150,7 +149,7 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
                     cachedInstance = response;
                 }
                 return response;
-            } catch(final InvocationTargetException e) {
+            } catch (final InvocationTargetException e) {
                 throw e.getCause();
             } finally {
                 if (isGetInstance) {
@@ -160,23 +159,21 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         }
     }
 
-    public void put(
-            final ModuleIdentifier moduleIdentifier,
-            final Module module,
-            final ModuleFactory moduleFactory,
+    public void put(final ModuleIdentifier moduleIdentifier, final Module module, final ModuleFactory moduleFactory,
             final ModuleInternalInfo maybeOldInternalInfo,
-            final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
-            final boolean isDefaultBean, final BundleContext bundleContext) {
+            final TransactionModuleJMXRegistration transactionModuleJMXRegistration, final boolean isDefaultBean,
+            final BundleContext bundleContext) {
         transactionStatus.checkNotCommitted();
 
         Class<? extends Module> moduleClass = Module.class;
         if (module instanceof RuntimeBeanRegistratorAwareModule) {
             moduleClass = RuntimeBeanRegistratorAwareModule.class;
         }
-        Module proxiedModule = Reflection.newProxy(moduleClass, new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
+        Module proxiedModule = Reflection.newProxy(moduleClass,
+                new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
         ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo(
-                moduleIdentifier, proxiedModule, moduleFactory,
-                maybeOldInternalInfo, transactionModuleJMXRegistration, isDefaultBean, module, bundleContext);
+                moduleIdentifier, proxiedModule, moduleFactory, maybeOldInternalInfo, transactionModuleJMXRegistration,
+                isDefaultBean, module, bundleContext);
         modulesHolder.put(moduleInternalTransactionalInfo);
     }
 
@@ -186,28 +183,25 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         return modulesHolder.toCommitInfo();
     }
 
-    public Module findModule(final ModuleIdentifier moduleIdentifier,
-                             final JmxAttribute jmxAttributeForReporting) {
-        return modulesHolder.findModule(moduleIdentifier,
-                jmxAttributeForReporting);
+    public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
+        return modulesHolder.findModule(moduleIdentifier, jmxAttributeForReporting);
     }
 
-    public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier) {
+    public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
+            final ModuleIdentifier moduleIdentifier) {
         return modulesHolder.findModuleInternalTransactionalInfo(moduleIdentifier);
     }
 
     public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
-                                           final JmxAttribute jmxAttributeForReporting) {
-        return modulesHolder.findModuleFactory(moduleIdentifier,
-                jmxAttributeForReporting);
+            final JmxAttribute jmxAttributeForReporting) {
+        return modulesHolder.findModuleFactory(moduleIdentifier, jmxAttributeForReporting);
     }
 
     public Map<ModuleIdentifier, Module> getAllModules() {
         return modulesHolder.getAllModules();
     }
 
-    public void assertNotExists(final ModuleIdentifier moduleIdentifier)
-            throws InstanceAlreadyExistsException {
+    public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
         modulesHolder.assertNotExists(moduleIdentifier);
     }
 
@@ -226,5 +220,4 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut
         modulesHolder.close();
         deadlockMonitor.close();
     }
-
 }
index d449e28dfe9b8a1268dfd40240932e7df6018b03..6f4ed6366a6d95383c6651184934c1794e1684d6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -31,7 +31,7 @@ public class DestroyedModule implements AutoCloseable,
     private final ModuleJMXRegistrator oldJMXRegistrator;
     private final OsgiRegistration osgiRegistration;
     private final int orderingIdx;
-    private RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
+    private final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
 
     public DestroyedModule(final ModuleIdentifier identifier, final AutoCloseable instance,
                            final ModuleJMXRegistrator oldJMXRegistrator,
@@ -46,6 +46,7 @@ public class DestroyedModule implements AutoCloseable,
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public void close() {
         LOG.trace("Destroying {}", identifier);
         try {
@@ -73,8 +74,8 @@ public class DestroyedModule implements AutoCloseable,
     }
 
     @Override
-    public int compareTo(final DestroyedModule o) {
-        return Integer.compare(orderingIdx, o.orderingIdx);
+    public int compareTo(final DestroyedModule destroyedModule) {
+        return Integer.compare(orderingIdx, destroyedModule.orderingIdx);
     }
 
     @Override
index 3a58b01b405387a6cba60467d170f76c8661d8c0..e8a6d512a47aae35602fa27138c91e6e45bbf943 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -34,7 +34,9 @@ public class ModuleInternalTransactionalInfo implements Identifiable<ModuleIdent
                                            final ModuleFactory moduleFactory,
                                            final ModuleInternalInfo maybeOldInternalInfo,
                                            final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
-                                           final boolean isDefaultBean, final Module realModule, final BundleContext bundleContext) {
+                                           final boolean isDefaultBean,
+                                           final Module realModule,
+                                           final BundleContext bundleContext) {
         this.name = name;
         this.proxiedModule = proxiedModule;
         this.moduleFactory = moduleFactory;
index cfe7ea14b9ae84c171a064a64f99a45b09b051f8..1132f991d171def6652f42c490b0956d4ea634a9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -40,41 +40,41 @@ class ModulesHolder implements AutoCloseable {
         this.transactionIdentifier = transactionIdentifier;
     }
 
-
     public CommitInfo toCommitInfo() {
         List<DestroyedModule> orderedDestroyedFromPreviousTransactions = new ArrayList<>(
                 unorderedDestroyedFromPreviousTransactions.size());
         for (ModuleInternalTransactionalInfo toBeDestroyed : unorderedDestroyedFromPreviousTransactions) {
-            orderedDestroyedFromPreviousTransactions.add(toBeDestroyed
-                    .toDestroyedModule());
+            orderedDestroyedFromPreviousTransactions.add(toBeDestroyed.toDestroyedModule());
         }
         Collections.sort(orderedDestroyedFromPreviousTransactions);
-        return new CommitInfo(orderedDestroyedFromPreviousTransactions,
-                commitMap);
+        return new CommitInfo(orderedDestroyedFromPreviousTransactions, commitMap);
     }
 
-    private ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
-            final ModuleIdentifier moduleIdentifier,
+    private ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier,
             final JmxAttribute jmxAttributeForReporting) {
-        ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = commitMap
-                .get(moduleIdentifier);
-        JmxAttributeValidationException.checkNotNull(
-                moduleInternalTransactionalInfo, "Module " + moduleIdentifier
-                        + "" + " not found in transaction " + transactionIdentifier,
+        ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = commitMap.get(moduleIdentifier);
+        JmxAttributeValidationException.checkNotNull(moduleInternalTransactionalInfo,
+                "Module " + moduleIdentifier + "" + " not found in transaction " + transactionIdentifier,
                 jmxAttributeForReporting);
         return moduleInternalTransactionalInfo;
     }
 
-    public Module findModule(final ModuleIdentifier moduleIdentifier,
-            final JmxAttribute jmxAttributeForReporting) {
-        return findModuleInternalTransactionalInfo(moduleIdentifier,
-                jmxAttributeForReporting).getProxiedModule();
+    public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
+            final ModuleIdentifier moduleIdentifier) {
+        ModuleInternalTransactionalInfo found = commitMap.get(moduleIdentifier);
+        if (found == null) {
+            throw new IllegalStateException("Not found:" + moduleIdentifier);
+        }
+        return found;
+    }
+
+    public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
+        return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getProxiedModule();
     }
 
     public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
             final JmxAttribute jmxAttributeForReporting) {
-        return findModuleInternalTransactionalInfo(moduleIdentifier,
-                jmxAttributeForReporting).getModuleFactory();
+        return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getModuleFactory();
     }
 
     public Map<ModuleIdentifier, Module> getAllModules() {
@@ -86,14 +86,11 @@ class ModulesHolder implements AutoCloseable {
         return result;
     }
 
-    public void put(
-            final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo) {
-        commitMap.put(moduleInternalTransactionalInfo.getIdentifier(),
-                moduleInternalTransactionalInfo);
+    public void put(final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo) {
+        commitMap.put(moduleInternalTransactionalInfo.getIdentifier(), moduleInternalTransactionalInfo);
     }
 
-    public ModuleInternalTransactionalInfo destroyModule(
-            final ModuleIdentifier moduleIdentifier) {
+    public ModuleInternalTransactionalInfo destroyModule(final ModuleIdentifier moduleIdentifier) {
         ModuleInternalTransactionalInfo found = commitMap.remove(moduleIdentifier);
         if (found == null) {
             throw new IllegalStateException("Not found:" + moduleIdentifier);
@@ -104,26 +101,16 @@ class ModulesHolder implements AutoCloseable {
         return found;
     }
 
-    public void assertNotExists(final ModuleIdentifier moduleIdentifier)
-            throws InstanceAlreadyExistsException {
+    public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
         if (commitMap.containsKey(moduleIdentifier)) {
-            throw new InstanceAlreadyExistsException(
-                    "There is an instance registered with name " + moduleIdentifier);
+            throw new InstanceAlreadyExistsException("There is an instance registered with name " + moduleIdentifier);
         }
     }
 
-    public Collection<ModuleInternalTransactionalInfo> getAllInfos(){
+    public Collection<ModuleInternalTransactionalInfo> getAllInfos() {
         return commitMap.values();
     }
 
-    public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier) {
-        ModuleInternalTransactionalInfo found = commitMap.get(moduleIdentifier);
-        if (found == null) {
-            throw new IllegalStateException("Not found:" + moduleIdentifier);
-        }
-        return found;
-    }
-
     @Override
     public void close() {
         unorderedDestroyedFromPreviousTransactions.clear();
index 638165a46c709c142c873c834014faf34ebf1572..e5bb549492708dd8542d909fdae21267c247246a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -53,7 +53,31 @@ import org.slf4j.LoggerFactory;
  * provides additional functionality - namely it disallows setting attribute on
  * a read only wrapper.
  */
-abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
+public abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
+
+    protected final Module module;
+    private final MBeanInfo mbeanInfo;
+    protected final ObjectName objectNameInternal;
+    protected final Map<String, AttributeHolder> attributeHolderMap;
+    protected final ModuleIdentifier moduleIdentifier;
+    protected final MBeanServer internalServer;
+
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
+
+    public AbstractDynamicWrapper(final Module module, final boolean writable, final ModuleIdentifier moduleIdentifier,
+            final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] operations,
+            final MBeanServer internalServer, final MBeanServer configMBeanServer) {
+        this.module = module;
+        this.moduleIdentifier = moduleIdentifier;
+        this.internalServer = internalServer;
+        this.objectNameInternal = thisWrapperObjectName;
+        // register the actual instance into an mbean server.
+        registerActualModule(objectNameInternal, configMBeanServer);
+        Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module.getClass());
+        this.attributeHolderMap = buildMBeanInfo(writable, moduleIdentifier, jmxInterfaces, objectNameInternal);
+        this.mbeanInfo = generateMBeanInfo(module, attributeHolderMap, operations, jmxInterfaces);
+    }
+
     private static final class ModuleNotificationListener implements NotificationListener {
         private final ObjectName objectNameInternal;
         private final MBeanServer internalServer;
@@ -67,72 +91,39 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
         }
 
         @Override
-        public void handleNotification(final Notification n, final Object handback) {
-            if (n instanceof MBeanServerNotification
-                    && n.getType()
-                        .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)
-                        && ((MBeanServerNotification) n).getMBeanName().equals(
-                        objectNameInternal)) {
+        public void handleNotification(final Notification notification, final Object handback) {
+            if (notification instanceof MBeanServerNotification
+                    && notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)
+                    && ((MBeanServerNotification) notification).getMBeanName().equals(objectNameInternal)) {
                 try {
                     internalServer.unregisterMBean(objectNameInternal);
-                    configMBeanServer.removeNotificationListener(
-                            MBeanServerDelegate.DELEGATE_NAME, this);
-                } catch (MBeanRegistrationException
-                        | ListenerNotFoundException
-                        | InstanceNotFoundException e) {
+                    configMBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this);
+                } catch (MBeanRegistrationException | ListenerNotFoundException | InstanceNotFoundException e) {
                     throw new IllegalStateException(e);
                 }
             }
         }
     }
 
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
-    protected final Module module;
-
-    private final MBeanInfo mbeanInfo;
-    protected final ObjectName objectNameInternal;
-    protected final Map<String, AttributeHolder> attributeHolderMap;
-    protected final ModuleIdentifier moduleIdentifier;
-    protected final MBeanServer internalServer;
-
-    public AbstractDynamicWrapper(final Module module, final boolean writable,
-                                  final ModuleIdentifier moduleIdentifier,
-                                  final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] dOperations,
-                                  final MBeanServer internalServer, final MBeanServer configMBeanServer) {
-
-        this.module = module;
-        this.moduleIdentifier = moduleIdentifier;
-        this.internalServer = internalServer;
-        this.objectNameInternal = thisWrapperObjectName;
-        // register the actual instance into an mbean server.
-        registerActualModule(objectNameInternal, configMBeanServer);
-        Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module
-                .getClass());
-        this.attributeHolderMap = buildMBeanInfo(writable,
-                moduleIdentifier, jmxInterfaces, objectNameInternal);
-        this.mbeanInfo = generateMBeanInfo(module,
-                attributeHolderMap, dOperations, jmxInterfaces);
-    }
-
     /**
      * Register module into an internal mbean server, attach listener to the
      * platform mbean server. Wait until this wrapper gets unregistered, in that
      * case unregister the module and remove listener.
      */
-    private final NotificationListener registerActualModule(final ObjectName objectNameInternal,
-                                                            final MBeanServer configMBeanServer) {
+    private NotificationListener registerActualModule(final ObjectName objectNameInternal,
+            final MBeanServer configMBeanServer) {
         try {
             internalServer.registerMBean(module, objectNameInternal);
-        } catch (InstanceAlreadyExistsException | MBeanRegistrationException
-                | NotCompliantMBeanException | IllegalStateException e) {
-            throw new IllegalStateException(
-                    "Error occured during mbean registration with name " + objectNameInternal, e);
+        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
+                | IllegalStateException e) {
+            throw new IllegalStateException("Error occured during mbean registration with name " + objectNameInternal,
+                    e);
         }
 
-        NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer, configMBeanServer);
+        NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer,
+                configMBeanServer);
         try {
-            configMBeanServer.addNotificationListener(
-                    MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
+            configMBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
         } catch (final InstanceNotFoundException e) {
             throw new RuntimeException("Could not add notification listener", e);
         }
@@ -140,24 +131,22 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
     }
 
     private static MBeanInfo generateMBeanInfo(final Module module,
-                                               final Map<String, AttributeHolder> attributeHolderMap,
-                                               final MBeanOperationInfo[] dOperations, final Set<Class<?>> jmxInterfaces) {
+            final Map<String, AttributeHolder> attributeHolderMap, final MBeanOperationInfo[] operations,
+            final Set<Class<?>> jmxInterfaces) {
 
-        String dDescription = findDescription(module.getClass(), jmxInterfaces);
-        MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[0];
-        List<MBeanAttributeInfo> attributes = new ArrayList<>(
-                attributeHolderMap.size());
+        String description = findDescription(module.getClass(), jmxInterfaces);
+        MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
+        List<MBeanAttributeInfo> attributes = new ArrayList<>(attributeHolderMap.size());
         for (AttributeHolder attributeHolder : attributeHolderMap.values()) {
             attributes.add(attributeHolder.toMBeanAttributeInfo());
         }
-        return new MBeanInfo(module.getClass().getName(), dDescription,
-                attributes.toArray(new MBeanAttributeInfo[0]), dConstructors,
-                dOperations, new MBeanNotificationInfo[0]);
+        return new MBeanInfo(module.getClass().getName(), description, attributes.toArray(new MBeanAttributeInfo[0]),
+                constructors, operations, new MBeanNotificationInfo[0]);
     }
 
     static String findDescription(final Class<?> clazz, final Set<Class<?>> jmxInterfaces) {
-        List<Description> descriptions = AnnotationsHelper
-                .findClassAnnotationInSuperClassesAndIfcs(clazz, Description.class, jmxInterfaces);
+        List<Description> descriptions = AnnotationsHelper.findClassAnnotationInSuperClassesAndIfcs(clazz,
+                Description.class, jmxInterfaces);
         return AnnotationsHelper.aggregateDescriptions(descriptions);
     }
 
@@ -168,8 +157,7 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
     // inspect all exported interfaces ending with MXBean, extract getters &
     // setters into attribute holder
     private Map<String, AttributeHolder> buildMBeanInfo(final boolean writable, final ModuleIdentifier moduleIdentifier,
-                                                               final Set<Class<?>> jmxInterfaces,
-                                                               final ObjectName internalObjectName) {
+            final Set<Class<?>> jmxInterfaces, final ObjectName internalObjectName) {
 
         // internal variables for describing MBean elements
         Set<Method> methods = new HashSet<>();
@@ -182,8 +170,7 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
         MBeanInfo internalInfo;
         try {
             internalInfo = internalServer.getMBeanInfo(internalObjectName);
-        } catch (InstanceNotFoundException | ReflectionException
-                | IntrospectionException e) {
+        } catch (InstanceNotFoundException | ReflectionException | IntrospectionException e) {
             throw new RuntimeException("MBean info not found", e);
         }
 
@@ -194,27 +181,21 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
         Map<String, AttributeHolder> attributeHolderMapLocal = new HashMap<>();
         for (Method method : methods) {
 
-            if (method.getParameterTypes().length == 1
-                    && method.getName().startsWith("set")) {
+            if (method.getParameterTypes().length == 1 && method.getName().startsWith("set")) {
                 Method setter;
                 String attribName = method.getName().substring(3);
                 try {
-                    setter = module.getClass().getMethod(method.getName(),
-                            method.getParameterTypes());
+                    setter = module.getClass().getMethod(method.getName(), method.getParameterTypes());
                 } catch (final NoSuchMethodException e) {
-                    throw new RuntimeException("No such method on "
-                            + moduleIdentifier, e);
+                    throw new RuntimeException("No such method on " + moduleIdentifier, e);
                 }
-                RequireInterface ifc = AttributeHolder
-                        .findRequireInterfaceAnnotation(setter, jmxInterfaces);
+                RequireInterface ifc = AttributeHolder.findRequireInterfaceAnnotation(setter, jmxInterfaces);
                 String description = null;
                 if (ifc != null) {
-                    description = AttributeHolder.findDescription(setter,
-                            jmxInterfaces);
+                    description = AttributeHolder.findDescription(setter, jmxInterfaces);
                 }
-                AttributeHolder attributeHolder = new AttributeHolder(
-                        attribName, module, attributeMap.get(attribName)
-                            .getType(), writable, ifc, description);
+                AttributeHolder attributeHolder = new AttributeHolder(attribName, module,
+                        attributeMap.get(attribName).getType(), writable, ifc, description);
                 attributeHolderMapLocal.put(attribName, attributeHolder);
             }
         }
@@ -230,30 +211,26 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
 
     @Override
     public Object getAttribute(final String attributeName)
-            throws AttributeNotFoundException, MBeanException,
-            ReflectionException {
+            throws AttributeNotFoundException, MBeanException, ReflectionException {
         if ("MBeanInfo".equals(attributeName)) {
             return getMBeanInfo();
         }
 
         Object obj = null;
         try {
-            obj = internalServer
-                    .getAttribute(objectNameInternal, attributeName);
+            obj = internalServer.getAttribute(objectNameInternal, attributeName);
         } catch (final InstanceNotFoundException e) {
-            new MBeanException(e);
+            throw new MBeanException(e);
         }
 
         if (obj instanceof ObjectName) {
-            AttributeHolder attributeHolder = attributeHolderMap
-                    .get(attributeName);
+            AttributeHolder attributeHolder = attributeHolderMap.get(attributeName);
             if (attributeHolder.getRequireInterfaceOrNull() != null) {
                 obj = fixObjectName((ObjectName) obj);
             }
             return obj;
         }
 
-
         if (isDependencyListAttr(attributeName, obj)) {
             obj = fixDependencyListAttribute(obj);
         }
@@ -263,14 +240,16 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
 
     private Object fixDependencyListAttribute(final Object attribute) {
         if (!attribute.getClass().isArray()) {
-            throw new IllegalArgumentException("Unexpected attribute type, should be an array, but was " + attribute.getClass());
+            throw new IllegalArgumentException(
+                    "Unexpected attribute type, should be an array, but was " + attribute.getClass());
         }
 
         for (int i = 0; i < Array.getLength(attribute); i++) {
 
             Object on = Array.get(attribute, i);
             if (!(on instanceof ObjectName)) {
-                throw new IllegalArgumentException("Unexpected attribute type, should be an ObjectName, but was " + on.getClass());
+                throw new IllegalArgumentException(
+                        "Unexpected attribute type, should be an ObjectName, but was " + on.getClass());
             }
             on = fixObjectName((ObjectName) on);
 
@@ -295,8 +274,8 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
 
     protected ObjectName fixObjectName(final ObjectName on) {
         if (!ObjectNameUtil.ON_DOMAIN.equals(on.getDomain())) {
-            throw new IllegalArgumentException("Wrong domain, expected "
-                    + ObjectNameUtil.ON_DOMAIN + " setter on " + on);
+            throw new IllegalArgumentException(
+                    "Wrong domain, expected " + ObjectNameUtil.ON_DOMAIN + " setter on " + on);
         }
         // if on contains transaction name, remove it
         String transactionName = ObjectNameUtil.getTransactionName(on);
@@ -311,11 +290,11 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
     public AttributeList getAttributes(final String[] attributes) {
         AttributeList result = new AttributeList();
         for (String attributeName : attributes) {
+            Object value;
             try {
-                Object value = getAttribute(attributeName);
+                value = getAttribute(attributeName);
                 result.add(new Attribute(attributeName, value));
-
-            } catch (final Exception e) {
+            } catch (AttributeNotFoundException | MBeanException | ReflectionException e) {
                 LOG.debug("Getting attribute {} failed", attributeName, e);
             }
         }
@@ -325,13 +304,11 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
     @Override
     public Object invoke(final String actionName, final Object[] params, final String[] signature)
             throws MBeanException, ReflectionException {
-        if ("getAttribute".equals(actionName) && params.length == 1
-                && signature[0].equals(String.class.getName())) {
+        if ("getAttribute".equals(actionName) && params.length == 1 && signature[0].equals(String.class.getName())) {
             try {
                 return getAttribute((String) params[0]);
             } catch (final AttributeNotFoundException e) {
-                throw new MBeanException(e, "Attribute not found on "
-                        + moduleIdentifier);
+                throw new MBeanException(e, "Attribute not found on " + moduleIdentifier);
             }
         } else if ("getAttributes".equals(actionName) && params.length == 1
                 && signature[0].equals(String[].class.getName())) {
@@ -341,10 +318,10 @@ abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
             return setAttributes((AttributeList) params[0]);
         } else {
             LOG.debug("Operation not found {} ", actionName);
-            throw new UnsupportedOperationException(
-                    String.format("Operation not found on %s. Method invoke is only supported for getInstance and getAttribute(s) "
+            throw new UnsupportedOperationException(String.format(
+                    "Operation not found on %s. Method invoke is only supported for getInstance and getAttribute(s) "
                             + "method, got actionName %s, params %s, signature %s ",
-                            moduleIdentifier, actionName, params, signature));
+                    moduleIdentifier, actionName, params, signature));
         }
     }
 
index e4a427746d45990ca4dcf94dd6066b0c22372a6f..f9548ae08e4d4e9685569ccb89f9c8a89d6599e0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -16,29 +16,27 @@ import java.util.List;
 import java.util.Set;
 import org.opendaylight.controller.config.api.annotations.Description;
 
-public class AnnotationsHelper {
+public final class AnnotationsHelper {
 
     private AnnotationsHelper() {
     }
 
     /**
      * Look for annotation specified by annotationType on method. First observe
-     * method's class, then its super classes, then all provided interfaces.
-     * Used for finding @Description and @RequireInterface
+     * method's class, then its super classes, then all provided interfaces. Used
+     * for finding @Description and @RequireInterface
      *
      * @param <T>
      *            generic type of annotation
      * @return list of found annotations
      */
-    static <T extends Annotation> List<T> findMethodAnnotationInSuperClassesAndIfcs(
-            final Method setter, final Class<T> annotationType,
-            final Set<Class<?>> inspectedInterfaces) {
+    static <T extends Annotation> List<T> findMethodAnnotationInSuperClassesAndIfcs(final Method setter,
+            final Class<T> annotationType, final Set<Class<?>> inspectedInterfaces) {
         Builder<T> result = ImmutableSet.builder();
         Class<?> inspectedClass = setter.getDeclaringClass();
         do {
             try {
-                Method foundSetter = inspectedClass.getMethod(setter.getName(),
-                        setter.getParameterTypes());
+                Method foundSetter = inspectedClass.getMethod(setter.getName(), setter.getParameterTypes());
                 T annotation = foundSetter.getAnnotation(annotationType);
                 if (annotation != null) {
                     result.add(annotation);
@@ -57,28 +55,27 @@ public class AnnotationsHelper {
                 throw new IllegalArgumentException(ifc + " is not an interface");
             }
             try {
-                Method foundSetter = ifc.getMethod(setter.getName(),
-                        setter.getParameterTypes());
+                Method foundSetter = ifc.getMethod(setter.getName(), setter.getParameterTypes());
                 T annotation = foundSetter.getAnnotation(annotationType);
                 if (annotation != null) {
                     result.add(annotation);
                 }
             } catch (final NoSuchMethodException e) {
-
+                break; // FIXME: is this ok?
             }
         }
         return new ArrayList<>(result.build());
     }
 
     /**
-     * Look for annotation specified by annotationType on type. First observe
-     * class clazz, then its super classes, then all exported interfaces with
-     * their super types. Used for finding @Description of modules.
+     * Look for annotation specified by annotationType on type. First observe class
+     * clazz, then its super classes, then all exported interfaces with their super
+     * types. Used for finding @Description of modules.
      *
      * @return list of found annotations
      */
-    static <T extends Annotation> List<T> findClassAnnotationInSuperClassesAndIfcs(
-            final Class<?> clazz, final Class<T> annotationType, final Set<Class<?>> interfaces) {
+    static <T extends Annotation> List<T> findClassAnnotationInSuperClassesAndIfcs(final Class<?> clazz,
+            final Class<T> annotationType, final Set<Class<?>> interfaces) {
         List<T> result = new ArrayList<>();
         Class<?> declaringClass = clazz;
         do {
@@ -102,6 +99,8 @@ public class AnnotationsHelper {
     }
 
     /**
+     * Lists aggregate descriptions.
+     *
      * @return empty string if no annotation is found, or list of descriptions
      *         separated by newline
      */
index 11d421c3b467e2993fb7b6c889399795c0449ab8..ff607d32e5f340319b050020998c23ded9e7c9d6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -38,10 +38,8 @@ class AttributeHolder {
         PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.add(List.class);
     }
 
-    public AttributeHolder(final String name, final Object object, final String returnType,
-                           final boolean writable,
-                           @Nullable final RequireInterface requireInterfaceAnnotation,
-                           final String description) {
+    AttributeHolder(final String name, final Object object, final String returnType, final boolean writable,
+            @Nullable final RequireInterface requireInterfaceAnnotation, final String description) {
         if (name == null) {
             throw new NullPointerException();
         }
@@ -57,13 +55,14 @@ class AttributeHolder {
     }
 
     public MBeanAttributeInfo toMBeanAttributeInfo() {
-        return new MBeanAttributeInfo(name, attributeType,
-                description, true, true, false);
+        return new MBeanAttributeInfo(name, attributeType, description, true, true, false);
     }
 
     /**
+     * Anotation.
+     *
      * @return annotation if setter sets ObjectName or ObjectName[], and is
-     * annotated. Return null otherwise.
+     *         annotated. Return null otherwise.
      */
     RequireInterface getRequireInterfaceOrNull() {
         return requireInterfaceAnnotation;
@@ -93,34 +92,37 @@ class AttributeHolder {
      * Find @Description annotations in method class and all its exported
      * interfaces.
      *
-     * @param setter
-     * @param jmxInterfaces
+     * @param setter setter method
+     * @param jmxInterfaces JMX interfaces
      * @return empty string if no annotation is found, or list of descriptions
-     * separated by newline
+     *         separated by newline
      */
     static String findDescription(final Method setter, final Set<Class<?>> jmxInterfaces) {
-        List<Description> descriptions = AnnotationsHelper
-                .findMethodAnnotationInSuperClassesAndIfcs(setter, Description.class, jmxInterfaces);
+        List<Description> descriptions = AnnotationsHelper.findMethodAnnotationInSuperClassesAndIfcs(setter,
+                Description.class, jmxInterfaces);
         return AnnotationsHelper.aggregateDescriptions(descriptions);
     }
 
     /**
-     * Find @RequireInterface annotation by searching method class and all
-     * exported interfaces.
+     * Find @RequireInterface annotation by searching method class and all exported
+     * interfaces.
      *
-     * @param setter
-     * @param inspectedInterfaces
+     * @param setter setter method
+     * @param inspectedInterfaces interfaces
      * @return null if no annotation is found, otherwise return the annotation
-     * @throws IllegalStateException    if more than one value is specified by found annotations
-     * @throws IllegalArgumentException if set of exported interfaces contains non interface type
+     * @throws IllegalStateException
+     *             if more than one value is specified by found annotations
+     * @throws IllegalArgumentException
+     *             if set of exported interfaces contains non interface type
      */
     static RequireInterface findRequireInterfaceAnnotation(final Method setter,
-                                                           final Set<Class<?>> inspectedInterfaces) {
+            final Set<Class<?>> inspectedInterfaces) {
 
-        // only allow setX(ObjectName y) or setX(ObjectName[] y) or setX(List<ObjectName> y) to continue
+        // only allow setX(ObjectName y) or setX(ObjectName[] y) or
+        // setX(List<ObjectName> y) to continue
 
-        if (setter.getParameterTypes().length > 1 ||
-                !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) {
+        if (setter.getParameterTypes().length > 1
+                || !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) {
             return null;
         }
 
@@ -135,10 +137,9 @@ class AttributeHolder {
         if (foundValues.isEmpty()) {
             return null;
         } else if (foundValues.size() > 1) {
-            throw new IllegalStateException("Error finding @RequireInterface. "
-                    + "More than one value specified as required interface "
-                    + foundValues + " of " + setter + " of "
-                    + setter.getDeclaringClass());
+            throw new IllegalStateException(
+                    "Error finding @RequireInterface. " + "More than one value specified as required interface "
+                            + foundValues + " of " + setter + " of " + setter.getDeclaringClass());
         } else {
             return foundRequireInterfaces.get(0);
         }
index 1a43d6f8842229671fb7a52439f938bf5d03a9eb..f768731e51b0afc6fc14dca19973d1cca2b78f35 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -27,12 +27,6 @@ public class DynamicReadableWrapper extends AbstractDynamicWrapper implements
         DynamicMBeanWithInstance {
     private final AutoCloseable instance;
 
-    /**
-     * @param module
-     * @param instance
-     *            for recreating Module.
-     *
-     */
     public DynamicReadableWrapper(final Module module, final AutoCloseable instance,
             final ModuleIdentifier moduleIdentifier, final MBeanServer internalServer,
             final MBeanServer configMBeanServer) {
index 90cc62358a80d641d60871b0ba824c104ab96c00..1ac299bcbb37ad3090e4dedc8d55b871cb55ad2d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -47,31 +47,27 @@ import org.slf4j.LoggerFactory;
  */
 @ThreadSafe
 public class DynamicWritableWrapper extends AbstractDynamicWrapper {
-    private static final Logger LOG = LoggerFactory
-            .getLogger(DynamicWritableWrapper.class);
+    private static final Logger LOG = LoggerFactory.getLogger(DynamicWritableWrapper.class);
 
     private final ReadOnlyAtomicBoolean configBeanModificationDisabled;
 
-    public DynamicWritableWrapper(final Module module,
-                                  final ModuleIdentifier moduleIdentifier,
-                                  final String transactionIdentifier,
-                                  final ReadOnlyAtomicBoolean configBeanModificationDisabled,
-                                  final MBeanServer internalServer, final MBeanServer configMBeanServer) {
-        super(module, true, moduleIdentifier, ObjectNameUtil
-                        .createTransactionModuleON(transactionIdentifier, moduleIdentifier), getOperations(moduleIdentifier),
-                internalServer, configMBeanServer);
+    public DynamicWritableWrapper(final Module module, final ModuleIdentifier moduleIdentifier,
+            final String transactionIdentifier, final ReadOnlyAtomicBoolean configBeanModificationDisabled,
+            final MBeanServer internalServer, final MBeanServer configMBeanServer) {
+        super(module, true, moduleIdentifier,
+                ObjectNameUtil.createTransactionModuleON(transactionIdentifier, moduleIdentifier),
+                getOperations(moduleIdentifier), internalServer, configMBeanServer);
         this.configBeanModificationDisabled = configBeanModificationDisabled;
     }
 
-    private static MBeanOperationInfo[] getOperations(
-            final ModuleIdentifier moduleIdentifier) {
+    private static MBeanOperationInfo[] getOperations(final ModuleIdentifier moduleIdentifier) {
         Method validationMethod;
         try {
             validationMethod = DynamicWritableWrapper.class.getMethod("validate");
         } catch (final NoSuchMethodException e) {
             throw new IllegalStateException("No such method exception on " + moduleIdentifier, e);
         }
-        return new MBeanOperationInfo[]{new MBeanOperationInfo("Validation", validationMethod)};
+        return new MBeanOperationInfo[] { new MBeanOperationInfo("Validation", validationMethod) };
     }
 
     @Override
@@ -105,7 +101,8 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
         Attribute newAttribute = attribute;
         AttributeHolder attributeHolder = attributeHolderMap.get(newAttribute.getName());
         if (attributeHolder.getRequireInterfaceOrNull() != null) {
-            newAttribute = new Attribute(newAttribute.getName(), fixObjectNames((ObjectName[]) newAttribute.getValue()));
+            newAttribute = new Attribute(newAttribute.getName(),
+                    fixObjectNames((ObjectName[]) newAttribute.getValue()));
         }
         return newAttribute;
     }
@@ -122,10 +119,10 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
     }
 
     private ObjectName[] fixObjectNames(final ObjectName[] dependencies) {
-        int i = 0;
+        int index = 0;
 
         for (ObjectName dependencyOn : dependencies) {
-            dependencies[i++] = fixObjectName(dependencyOn);
+            dependencies[index++] = fixObjectName(dependencyOn);
         }
 
         return dependencies;
@@ -139,28 +136,26 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
             try {
                 setAttribute(attribute);
                 result.add(attribute);
-            } catch (final Exception e) {
+            } catch (final InvalidAttributeValueException | AttributeNotFoundException | MBeanException
+                    | ReflectionException e) {
                 LOG.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
                 throw new IllegalArgumentException(
-                        "Setting attribute failed - " + attribute.getName()
-                                + " on " + moduleIdentifier, e);
+                        "Setting attribute failed - " + attribute.getName() + " on " + moduleIdentifier, e);
             }
         }
         return result;
     }
 
+    @SuppressWarnings("IllegalCatch")
     @Override
     public Object invoke(final String actionName, final Object[] params, final String[] signature)
             throws MBeanException, ReflectionException {
-        if ("validate".equals(actionName)
-                && (params == null || params.length == 0)
+        if ("validate".equals(actionName) && (params == null || params.length == 0)
                 && (signature == null || signature.length == 0)) {
             try {
                 validate();
             } catch (final Exception e) {
-
-                throw new MBeanException(ValidationException.createForSingleException(
-                        moduleIdentifier, e));
+                throw new MBeanException(ValidationException.createForSingleException(moduleIdentifier, e));
             }
             return Void.TYPE;
         }
index 63be03f8ad228c5cd8ac08b0f2f926d482f343a9..e07d0d76e1b4f35bf79b4aafd7a0628b01e389ea 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -31,17 +31,17 @@ public class HierarchicalConfigMBeanFactoriesHolder {
     /**
      * Create instance.
      *
+     * @param factoriesMap map of factories
      * @throws IllegalArgumentException
      *             if unique constraint on module names is violated
      */
     public HierarchicalConfigMBeanFactoriesHolder(
             final Map<String, Map.Entry<ModuleFactory, BundleContext>> factoriesMap) {
-        this.moduleNamesToConfigBeanFactories = Collections
-                .unmodifiableMap(factoriesMap);
-        moduleNames = Collections.unmodifiableSet(new TreeSet<>(
-                moduleNamesToConfigBeanFactories.keySet()));
+        this.moduleNamesToConfigBeanFactories = Collections.unmodifiableMap(factoriesMap);
+        moduleNames = Collections.unmodifiableSet(new TreeSet<>(moduleNamesToConfigBeanFactories.keySet()));
         List<ModuleFactory> factories = new ArrayList<>(this.moduleNamesToConfigBeanFactories.size());
-        Collection<Map.Entry<ModuleFactory, BundleContext>> entryCollection = this.moduleNamesToConfigBeanFactories.values();
+        Collection<Map.Entry<ModuleFactory, BundleContext>> entryCollection = this.moduleNamesToConfigBeanFactories
+                .values();
         for (Map.Entry<ModuleFactory, BundleContext> entry : entryCollection) {
             factories.add(entry.getKey());
         }
@@ -51,6 +51,9 @@ public class HierarchicalConfigMBeanFactoriesHolder {
     /**
      * Get ModuleFactory by their name.
      *
+     * @param moduleName
+     *            module name
+     * @return module factory
      * @throws IllegalArgumentException
      *             if factory is not found
      */
@@ -69,5 +72,4 @@ public class HierarchicalConfigMBeanFactoriesHolder {
     public List<ModuleFactory> getModuleFactories() {
         return moduleFactories;
     }
-
 }
index 7d0bee25333b84148bfce23e1c09380e169b2149..f4b326ea19bda835075947f625bd631a1dcdabfe 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -88,7 +88,8 @@ abstract class InternalJMXRegistrator implements AutoCloseable {
     final synchronized void unregisterMBean(final ObjectName on) {
         // first check that on was registered using this instance
         boolean removed = registeredObjectNames.remove(on);
-        Preconditions.checkState(removed, "Cannot unregister - ObjectName not found in 'registeredObjectNames': %s", on);
+        Preconditions.checkState(removed, "Cannot unregister - ObjectName not found in 'registeredObjectNames': %s",
+                on);
 
         try {
             getMBeanServer().unregisterMBean(on);
@@ -159,7 +160,7 @@ abstract class InternalJMXRegistrator implements AutoCloseable {
         for (ObjectName on : registeredObjectNames) {
             try {
                 getMBeanServer().unregisterMBean(on);
-            } catch (final Exception e) {
+            } catch (final InstanceNotFoundException | MBeanRegistrationException e) {
                 LOG.warn("Ignoring error while unregistering {}", on, e);
             }
         }
index 1492d5de91ed26ade1c7f6def96168acce72d513..a4fcdbbf8e97e40fc1db1672e6cba0ba728c43c7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,19 +26,19 @@ import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotific
 import org.opendaylight.controller.config.manager.impl.ConfigRegistryImplMXBean;
 
 /**
- * Thin wrapper over ConfigRegistry emitting JMX notifications
+ * Thin wrapper over ConfigRegistry emitting JMX notifications.
  */
 public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, AutoCloseable {
 
     private final ConfigRegistryImplMXBean delegate;
     private final NotifierMXBeanImpl notifier;
-    private final MBeanServer mBeanServer;
+    private final MBeanServer beanServer;
 
-    public JMXNotifierConfigRegistry(final ConfigRegistryImplMXBean delegate, final MBeanServer mBeanServer) {
+    public JMXNotifierConfigRegistry(final ConfigRegistryImplMXBean delegate, final MBeanServer beanServer) {
         this.delegate = delegate;
         notifier = new NotifierMXBeanImpl();
-        this.mBeanServer = mBeanServer;
-        registerMBean(notifier, this.mBeanServer, ConfigJMXNotification.OBJECT_NAME);
+        this.beanServer = beanServer;
+        registerMBean(notifier, this.beanServer, ConfigJMXNotification.OBJECT_NAME);
     }
 
     private static void registerMBean(final Object instance, final MBeanServer mbs, final ObjectName on) {
@@ -60,7 +60,8 @@ public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, Auto
     }
 
     @Override
-    public CommitStatus commitConfig(final ObjectName transactionControllerON) throws ConflictingVersionException, ValidationException {
+    public CommitStatus commitConfig(final ObjectName transactionControllerON)
+            throws ConflictingVersionException, ValidationException {
         final CommitStatus commitStatus = delegate.commitConfig(transactionControllerON);
         notifier.notifyCommit(ObjectNameUtil.getTransactionName(transactionControllerON));
         return commitStatus;
@@ -97,7 +98,8 @@ public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, Auto
     }
 
     @Override
-    public ObjectName lookupConfigBean(final String moduleName, final String instanceName) throws InstanceNotFoundException {
+    public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+            throws InstanceNotFoundException {
         return delegate.lookupConfigBean(moduleName, instanceName);
     }
 
@@ -147,7 +149,8 @@ public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, Auto
     }
 
     @Override
-    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
+    public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
+            throws InstanceNotFoundException {
         return delegate.getServiceReference(serviceInterfaceQName, refName);
     }
 
@@ -159,13 +162,15 @@ public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, Auto
     @Override
     public void close() {
         try {
-            mBeanServer.unregisterMBean(ConfigJMXNotification.OBJECT_NAME);
+            beanServer.unregisterMBean(ConfigJMXNotification.OBJECT_NAME);
         } catch (InstanceNotFoundException | MBeanRegistrationException e) {
-            throw new IllegalStateException("Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing");
+            throw new IllegalStateException(
+                    "Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing");
         }
     }
 
-    public interface NotifierMXBean {}
+    public interface NotifierMXBean {
+    }
 
     public static class NotifierMXBeanImpl extends NotificationBroadcasterSupport implements NotifierMXBean {
 
index 1f29a656045282cf0989baa2125b56ca31b9c247..e84d2ee953efdc2c46bd8e4ee465500fac146653 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -16,8 +16,7 @@ import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
 import org.opendaylight.controller.config.api.runtime.RuntimeBean;
 
-public class RootRuntimeBeanRegistratorImpl implements
-        RootRuntimeBeanRegistrator {
+public class RootRuntimeBeanRegistratorImpl implements RootRuntimeBeanRegistrator {
     private final InternalJMXRegistrator internalJMXRegistrator;
     private final ModuleIdentifier moduleIdentifier;
     private final ObjectName defaultRuntimeON;
@@ -26,10 +25,8 @@ public class RootRuntimeBeanRegistratorImpl implements
             final ModuleIdentifier moduleIdentifier) {
         this.internalJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
         this.moduleIdentifier = moduleIdentifier;
-        defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(
-                moduleIdentifier.getFactoryName(),
-                moduleIdentifier.getInstanceName(),
-                Collections.<String, String> emptyMap());
+        defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(moduleIdentifier.getFactoryName(),
+                moduleIdentifier.getInstanceName(), Collections.<String, String>emptyMap());
     }
 
     @Override
@@ -39,8 +36,8 @@ public class RootRuntimeBeanRegistratorImpl implements
         } catch (final InstanceAlreadyExistsException e) {
             throw sanitize(e, moduleIdentifier, defaultRuntimeON);
         }
-        return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier,
-                internalJMXRegistrator, Collections.<String, String> emptyMap());
+        return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier, internalJMXRegistrator,
+                Collections.<String, String>emptyMap());
     }
 
     @Override
@@ -48,10 +45,9 @@ public class RootRuntimeBeanRegistratorImpl implements
         internalJMXRegistrator.close();
     }
 
-    static IllegalStateException sanitize(final InstanceAlreadyExistsException e,
+    static IllegalStateException sanitize(final InstanceAlreadyExistsException exception,
             final ModuleIdentifier moduleIdentifier, final ObjectName on) {
-        throw new IllegalStateException("Could not register runtime bean in "
-                + moduleIdentifier + " under name " + on, e);
-
+        throw new IllegalStateException("Could not register runtime bean in " + moduleIdentifier + " under name " + on,
+                exception);
     }
 }
index 9388b8e567d256eea035047da2d5552f0bc7b17f..88646b4cc1b759b95cede46d7db99103103bc57a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -25,15 +25,15 @@ public class ServiceReference {
     }
 
     @Override
-    public boolean equals(final Object o) {
-        if (this == o) {
+    public boolean equals(final Object object) {
+        if (this == object) {
             return true;
         }
-        if (o == null || getClass() != o.getClass()) {
+        if (object == null || getClass() != object.getClass()) {
             return false;
         }
 
-        ServiceReference that = (ServiceReference) o;
+        ServiceReference that = (ServiceReference) object;
 
         if (!refName.equals(that.refName)) {
             return false;
@@ -54,9 +54,7 @@ public class ServiceReference {
 
     @Override
     public String toString() {
-        return "ServiceReference{" +
-                "serviceInterfaceName='" + serviceInterfaceName + '\'' +
-                ", refName='" + refName + '\'' +
-                '}';
+        return "ServiceReference{" + "serviceInterfaceName='" + serviceInterfaceName + '\'' + ", refName='" + refName
+                + '\'' + '}';
     }
 }
index e9db0715e5758f239bc2cffa397e5846f5a3e1cd..5dc3fe2ecaa80f70e93f1c39e4e0e211dda6f6eb 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -15,8 +15,8 @@ public interface ServiceReferenceRegistrator extends AutoCloseable {
 
     String getNullableTransactionName();
 
-    ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object,
-                                                          ObjectName on) throws InstanceAlreadyExistsException;
+    ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on)
+            throws InstanceAlreadyExistsException;
 
     @Override
     void close();
@@ -42,7 +42,8 @@ public interface ServiceReferenceRegistrator extends AutoCloseable {
         private final InternalJMXRegistrator currentJMXRegistrator;
         private final String nullableTransactionName;
 
-        public ServiceReferenceRegistratorImpl(final NestableJMXRegistrator parentRegistrator, final String nullableTransactionName){
+        public ServiceReferenceRegistratorImpl(final NestableJMXRegistrator parentRegistrator,
+                final String nullableTransactionName) {
             currentJMXRegistrator = parentRegistrator.createChild();
             this.nullableTransactionName = nullableTransactionName;
         }
@@ -52,14 +53,13 @@ public interface ServiceReferenceRegistrator extends AutoCloseable {
             return nullableTransactionName;
         }
 
-
         @Override
         public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object,
-                                                             final ObjectName on) throws InstanceAlreadyExistsException {
+                final ObjectName on) throws InstanceAlreadyExistsException {
             String actualTransactionName = ObjectNameUtil.getTransactionName(on);
             boolean broken = false;
-            broken |= (nullableTransactionName == null) != (actualTransactionName == null);
-            broken |= (nullableTransactionName != null) && !nullableTransactionName.equals(actualTransactionName);
+            broken |= nullableTransactionName == null != (actualTransactionName == null);
+            broken |= nullableTransactionName != null && !nullableTransactionName.equals(actualTransactionName);
             if (broken) {
                 throw new IllegalArgumentException("Transaction name mismatch between expected "
                         + nullableTransactionName + ", got " + actualTransactionName + " in " + on);
@@ -70,23 +70,22 @@ public interface ServiceReferenceRegistrator extends AutoCloseable {
             return new ServiceReferenceJMXRegistration(currentJMXRegistrator.registerMBean(object, on));
         }
 
-
         @Override
         public void close() {
             currentJMXRegistrator.close();
         }
+
         public interface ServiceReferenceTransactionRegistratorFactory {
             ServiceReferenceRegistrator create();
         }
     }
 
-
     class ServiceReferenceTransactionRegistratorFactoryImpl implements ServiceReferenceTransactionRegistratorFactory {
         private final NestableJMXRegistrator parentRegistrator;
         private final String nullableTransactionName;
 
-        public ServiceReferenceTransactionRegistratorFactoryImpl(final TransactionModuleJMXRegistrator parentRegistrator,
-                                                             final String nullableTransactionName) {
+        public ServiceReferenceTransactionRegistratorFactoryImpl(
+                final TransactionModuleJMXRegistrator parentRegistrator, final String nullableTransactionName) {
             this.parentRegistrator = parentRegistrator;
             this.nullableTransactionName = nullableTransactionName;
         }
index ff504dafdcac22176d798569836bfe6e5ce460c7..9031f23462b520fe7fc8f92e8a8be174a5b06a0c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -30,13 +30,19 @@ public class BeanToOsgiServiceManager {
     private static final String SERVICE_NAME_OSGI_PROP = "name";
 
     /**
-     * To be called for every created, reconfigured and recreated config bean.
-     * It is expected that before using this method OSGi service registry will
-     * be cleaned from previous registrations.
+     * To be called for every created, reconfigured and recreated config bean. It is
+     * expected that before using this method OSGi service registry will be cleaned
+     * from previous registrations.
+     *
+     * @param instance instance
+     * @param moduleIdentifier module identifier
+     * @param bundleContext bundle context
+     * @param serviceNamesToAnnotations service names annotations
+     * @return OSGI registration
      */
     public OsgiRegistration registerToOsgi(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
-                                           final BundleContext bundleContext,
-                                           final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+            final BundleContext bundleContext,
+            final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations) {
         return new OsgiRegistration(instance, moduleIdentifier, bundleContext, serviceNamesToAnnotations);
     }
 
@@ -49,34 +55,36 @@ public class BeanToOsgiServiceManager {
         @GuardedBy("this")
         private final Set<ServiceRegistration<?>> serviceRegistrations;
         @GuardedBy("this")
-        private final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations;
+        private final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations;
 
         public OsgiRegistration(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
-                                final BundleContext bundleContext,
-                                final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+                final BundleContext bundleContext,
+                final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
             this.instance = instance;
             this.moduleIdentifier = moduleIdentifier;
             this.serviceNamesToAnnotations = serviceNamesToAnnotations;
             this.serviceRegistrations = registerToSR(instance, bundleContext, serviceNamesToAnnotations);
         }
 
-        private static Set<ServiceRegistration<?>> registerToSR(final AutoCloseable instance, final BundleContext bundleContext,
-                                                                final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+        private static Set<ServiceRegistration<?>> registerToSR(final AutoCloseable instance,
+                final BundleContext bundleContext,
+                final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
             Set<ServiceRegistration<?>> serviceRegistrations = new HashSet<>();
-            for (Entry<ServiceInterfaceAnnotation, String /* service ref name */> entry : serviceNamesToAnnotations.entrySet()) {
+            for (Entry<ServiceInterfaceAnnotation, String /* service ref name */> entry : serviceNamesToAnnotations
+                    .entrySet()) {
                 ServiceInterfaceAnnotation annotation = entry.getKey();
                 Class<?> requiredInterface = annotation.osgiRegistrationType();
 
-                if(!annotation.registerToOsgi()) {
+                if (!annotation.registerToOsgi()) {
                     LOG.debug("registerToOsgi for service interface {} is false - not registering", requiredInterface);
                     continue;
                 }
 
-                Preconditions.checkState(requiredInterface.isInstance(instance), instance.getClass().getName() +
-                        " instance should implement " + requiredInterface.getName());
+                Preconditions.checkState(requiredInterface.isInstance(instance),
+                        instance.getClass().getName() + " instance should implement " + requiredInterface.getName());
                 Dictionary<String, String> propertiesForOsgi = createProps(entry.getValue());
-                ServiceRegistration<?> serviceRegistration = bundleContext
-                        .registerService(requiredInterface.getName(), instance, propertiesForOsgi);
+                ServiceRegistration<?> serviceRegistration = bundleContext.registerService(requiredInterface.getName(),
+                        instance, propertiesForOsgi);
                 serviceRegistrations.add(serviceRegistration);
             }
             return serviceRegistrations;
@@ -87,19 +95,21 @@ public class BeanToOsgiServiceManager {
             for (ServiceRegistration<?> serviceRegistration : serviceRegistrations) {
                 try {
                     serviceRegistration.unregister();
-                } catch(final IllegalStateException e) {
+                } catch (final IllegalStateException e) {
                     LOG.trace("Cannot unregister {}", serviceRegistration, e);
                 }
             }
             serviceRegistrations.clear();
         }
 
-        public synchronized void updateRegistrations(final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
-                                                     final BundleContext bundleContext, final AutoCloseable newInstance) {
+        public synchronized void updateRegistrations(
+                final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
+                final BundleContext bundleContext, final AutoCloseable newInstance) {
             boolean notEquals = !this.instance.equals(newInstance);
             notEquals |= !newAnnotationMapping.equals(serviceNamesToAnnotations);
             if (notEquals) {
-                // FIXME: changing from old state to new state can be improved by computing the diff
+                // FIXME: changing from old state to new state can be improved by computing the
+                // diff
                 LOG.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
                         serviceNamesToAnnotations, newAnnotationMapping);
                 close();
index 8ec44a14ba5219a98b7f486112535a4286b2c959..2649b145d0509badbcd88897ca99a83282bed6b5 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -23,9 +23,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Every time factory is added or removed, blank transaction is triggered to handle
- * {@link org.opendaylight.controller.config.spi.ModuleFactory#getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory, org.osgi.framework.BundleContext)}
- * functionality.
+ * Every time factory is added or removed, blank transaction is triggered to
+ * handle.
  */
 public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<ModuleFactory, Object> {
     private static final Logger LOG = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
@@ -40,12 +39,12 @@ public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<
         this(() -> {
             ObjectName tx = configRegistry.beginConfig(true);
             return configRegistry.commitConfig(tx);
-         });
+        });
     }
 
     public BlankTransactionServiceTracker(final BlankTransaction blankTransaction) {
-        this(blankTransaction, DEFAULT_MAX_ATTEMPTS, Executors.newSingleThreadExecutor(new ThreadFactoryBuilder()
-                .setNameFormat("config-blank-txn-%d").build()));
+        this(blankTransaction, DEFAULT_MAX_ATTEMPTS, Executors
+                .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("config-blank-txn-%d").build()));
     }
 
     @VisibleForTesting
@@ -67,7 +66,8 @@ public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<
     }
 
     void blankTransactionSync() {
-        // race condition check: config-persister might push new configuration while server is starting up.
+        // race condition check: config-persister might push new configuration while
+        // server is starting up.
         ConflictingVersionException lastException = null;
         for (int i = 0; i < maxAttempts; i++) {
             try {
@@ -94,12 +94,14 @@ public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<
     }
 
     @Override
-    public void modifiedService(final ServiceReference <ModuleFactory> moduleFactoryServiceReference, final Object o) {
+    public void modifiedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
+            final Object object) {
         blankTransactionAsync();
     }
 
     @Override
-    public void removedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference, final Object o) {
+    public void removedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
+            final Object object) {
         blankTransactionAsync();
     }
 
index 1926c6b9af3e4adbed9acf27bb9cd44007ed2e3e..28f512d848f9b03fc5abbd1fc1cb7d3da7660535 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,8 +26,7 @@ public class BundleContextBackedModuleFactoriesResolver implements ModuleFactori
     private static final Logger LOG = LoggerFactory.getLogger(BundleContextBackedModuleFactoriesResolver.class);
     private final BundleContext bundleContext;
 
-    public BundleContextBackedModuleFactoriesResolver(
-            final BundleContext bundleContext) {
+    public BundleContextBackedModuleFactoriesResolver(final BundleContext bundleContext) {
         this.bundleContext = bundleContext;
     }
 
@@ -47,13 +46,13 @@ public class BundleContextBackedModuleFactoriesResolver implements ModuleFactori
             // implement the classes under which it was registered or the
             // ServiceFactory threw an exception.
             if (factory == null) {
-                throw new NullPointerException("ServiceReference of class" + serviceReference.getClass() + "not found.");
+                throw new NullPointerException(
+                        "ServiceReference of class" + serviceReference.getClass() + "not found.");
             }
 
             String moduleName = factory.getImplementationName();
             if (moduleName == null || moduleName.isEmpty()) {
-                throw new IllegalStateException(
-                        "Invalid implementation name for " + factory);
+                throw new IllegalStateException("Invalid implementation name for " + factory);
             }
             if (serviceReference.getBundle() == null || serviceReference.getBundle().getBundleContext() == null) {
                 throw new NullPointerException("Bundle context of " + factory + " ModuleFactory not found.");
@@ -63,14 +62,14 @@ public class BundleContextBackedModuleFactoriesResolver implements ModuleFactori
             Map.Entry<ModuleFactory, BundleContext> conflicting = result.get(moduleName);
             if (conflicting != null) {
                 String error = String.format(
-                    "Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
-                    moduleName, conflicting.getKey(), factory);
+                        "Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
+                        moduleName, conflicting.getKey(), factory);
                 LOG.error(error);
                 throw new IllegalArgumentException(error);
             }
 
-            result.put(moduleName, new AbstractMap.SimpleImmutableEntry<>(factory,
-                    serviceReference.getBundle().getBundleContext()));
+            result.put(moduleName,
+                    new AbstractMap.SimpleImmutableEntry<>(factory, serviceReference.getBundle().getBundleContext()));
         }
         return result;
     }
index eba7ad1a05314b572081fdd41c98b541f11f220c..d1c3d767bfebfdf7bc2e72b1a292af464ca0aadf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -62,13 +62,14 @@ public class ConfigManagerActivator implements BundleActivator, SynchronousBundl
                     moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext,
                     bindingContextProvider, context);
 
-            final ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker(moduleInfoRegistryWrapper);
+            final ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker(
+                    moduleInfoRegistryWrapper);
 
             // start config registry
             final BundleContextBackedModuleFactoriesResolver bundleContextBackedModuleFactoriesResolver =
                     new BundleContextBackedModuleFactoriesResolver(context);
             this.configRegistry = new ConfigRegistryImpl(bundleContextBackedModuleFactoriesResolver,
-                this.configMBeanServer, bindingContextProvider);
+                    this.configMBeanServer, bindingContextProvider);
 
             // track bundles containing factories
             final BlankTransactionServiceTracker blankTransactionServiceTracker = new BlankTransactionServiceTracker(
@@ -78,7 +79,7 @@ public class ConfigManagerActivator implements BundleActivator, SynchronousBundl
 
             BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> moduleInfoResolvedBundleTracker =
                     new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE,
-                            moduleInfoBundleTracker);
+                    moduleInfoBundleTracker);
             ExtensibleBundleTracker<?> moduleFactoryBundleTracker = new ExtensibleBundleTracker<>(context,
                     moduleFactoryTracker);
             moduleInfoBundleTracker.open(moduleInfoResolvedBundleTracker);
@@ -87,18 +88,18 @@ public class ConfigManagerActivator implements BundleActivator, SynchronousBundl
             moduleFactoryBundleTracker.open();
 
             // Wrap config registry with JMX notification publishing adapter
-            final JMXNotifierConfigRegistry notifyingConfigRegistry =
-                    new JMXNotifierConfigRegistry(this.configRegistry, this.configMBeanServer);
+            final JMXNotifierConfigRegistry notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry,
+                    this.configMBeanServer);
 
             // register config registry to OSGi
             final AutoCloseable clsReg = OsgiRegistrationUtil.registerService(context, moduleInfoBackedContext,
-                ClassLoadingStrategy.class);
+                    ClassLoadingStrategy.class);
             final AutoCloseable configRegReg = OsgiRegistrationUtil.registerService(context, notifyingConfigRegistry,
-                ConfigRegistry.class);
+                    ConfigRegistry.class);
 
             // register config registry to jmx
-            final ConfigRegistryJMXRegistrator configRegistryJMXRegistrator =
-                    new ConfigRegistryJMXRegistrator(this.configMBeanServer);
+            final ConfigRegistryJMXRegistrator configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
+                    this.configMBeanServer);
             try {
                 configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
             } catch (final InstanceAlreadyExistsException e) {
@@ -123,23 +124,18 @@ public class ConfigManagerActivator implements BundleActivator, SynchronousBundl
             serviceTracker.open();
 
             final AutoCloseable configMgrReg = OsgiRegistrationUtil.registerService(context, this,
-                ConfigSystemService.class);
+                    ConfigSystemService.class);
 
             final List<AutoCloseable> list = Arrays.asList(bindingContextProvider, clsReg,
-                    OsgiRegistrationUtil.wrap(moduleFactoryBundleTracker), moduleInfoBundleTracker,
-                    configRegReg, configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications,
+                    OsgiRegistrationUtil.wrap(moduleFactoryBundleTracker), moduleInfoBundleTracker, configRegReg,
+                    configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications,
                     OsgiRegistrationUtil.wrap(serviceTracker), moduleInfoRegistryWrapper, notifyingConfigRegistry,
                     configMgrReg);
             this.autoCloseable = OsgiRegistrationUtil.aggregate(list);
 
             context.addBundleListener(this);
-        } catch(final Exception e) {
-            LOG.error("Error starting config manager", e);
-        } catch(final Error e) {
-            // Log JVM Error and re-throw. The OSGi container may silently fail the bundle and not always log
-            // the exception. This has been seen on initial feature install.
+        } catch (final IllegalStateException e) {
             LOG.error("Error starting config manager", e);
-            throw e;
         }
 
         LOG.info("Config manager start complete");
@@ -154,20 +150,21 @@ public class ConfigManagerActivator implements BundleActivator, SynchronousBundl
 
     @Override
     public void bundleChanged(final BundleEvent event) {
-        if(this.configRegistry == null) {
+        if (this.configRegistry == null) {
             return;
         }
 
-        // If the system bundle (id 0) is stopping close the ConfigRegistry so it destroys all modules. On
+        // If the system bundle (id 0) is stopping close the ConfigRegistry so it
+        // destroys all modules. On
         // shutdown the system bundle is stopped first.
-        if(event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
+        if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
             this.configRegistry.close();
         }
     }
 
     @Override
     public void closeAllConfigModules() {
-        if(this.configRegistry != null) {
+        if (this.configRegistry != null) {
             this.configRegistry.close();
         }
     }
index 5841acfde8683541efdb3de605f548627a0593bc..132005ac7c4a426f1e96c24399e9c4ac0157fdd2 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.config.manager.impl.osgi;
 
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
@@ -20,42 +21,44 @@ import org.osgi.util.tracker.BundleTrackerCustomizer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-
 /**
- *
  * Extensible bundle tracker. Takes several BundleTrackerCustomizers and
  * propagates bundle events to all of them.
  *
- * Primary customizer may return tracking object,
- * which will be passed to it during invocation of
+ * <p>
+ * Primary customizer may return tracking object, which will be passed to it
+ * during invocation of
  * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)}
  *
+ * <p>
+ * This extender modifies behavior to not leak platform thread in
+ * {@link BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)} but deliver
+ * this event from its own single threaded executor.
  *
- * This extender modifies behaviour to not leak platform thread
- * in {@link BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)}
- * but deliver this event from its own single threaded executor.
- *
- * If bundle is removed before event for adding bundle was executed,
- * that event is cancelled. If addingBundle event is currently in progress
- * or was already executed, platform thread is block untill addingBundle
- * finishes so bundle could be removed correctly in platform thread.
- *
+ * <p>
+ * If bundle is removed before event for adding bundle was executed, that event
+ * is cancelled. If addingBundle event is currently in progress or was already
+ * executed, platform thread is block until addingBundle finishes so bundle
+ * could be removed correctly in platform thread.
  *
- * Method {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)}
- * is never invoked on registered trackers.
+ * <p>
+ * Method
+ * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} is
+ * never invoked on registered trackers.
  *
- * @param <T>
+ * @param <T> value
  */
 public final class ExtensibleBundleTracker<T> extends BundleTracker<Future<T>> {
     private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
-        .setNameFormat("config-bundle-tracker-%d").build();
+            .setNameFormat("config-bundle-tracker-%d").build();
     private final ExecutorService eventExecutor;
     private final BundleTrackerCustomizer<T> primaryTracker;
     private final BundleTrackerCustomizer<?>[] additionalTrackers;
 
     private static final Logger LOG = LoggerFactory.getLogger(ExtensibleBundleTracker.class);
 
-    public ExtensibleBundleTracker(final BundleContext context, final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
+    public ExtensibleBundleTracker(final BundleContext context,
+            final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
             final BundleTrackerCustomizer<?>... additionalBundleTrackerCustomizers) {
         this(context, Bundle.ACTIVE, primaryBundleTrackerCustomizer, additionalBundleTrackerCustomizers);
     }
@@ -72,41 +75,35 @@ public final class ExtensibleBundleTracker<T> extends BundleTracker<Future<T>> {
 
     @Override
     public Future<T> addingBundle(final Bundle bundle, final BundleEvent event) {
-        LOG.trace("Submiting AddingBundle for bundle {} and event {} to be processed asynchronously",bundle,event);
+        LOG.trace("Submiting AddingBundle for bundle {} and event {} to be processed asynchronously", bundle, event);
         return eventExecutor.submit(() -> {
-            try {
-                T primaryTrackerRetVal = primaryTracker.addingBundle(bundle, event);
+            T primaryTrackerRetVal = primaryTracker.addingBundle(bundle, event);
 
-                forEachAdditionalBundle(tracker -> tracker.addingBundle(bundle, event));
-                LOG.trace("AddingBundle for {} and event {} finished successfully",bundle,event);
-                return primaryTrackerRetVal;
-            } catch (final Exception e) {
-                LOG.error("Failed to add bundle {}", bundle, e);
-                throw e;
-            }
+            forEachAdditionalBundle(tracker -> tracker.addingBundle(bundle, event));
+            LOG.trace("AddingBundle for {} and event {} finished successfully", bundle, event);
+            return primaryTrackerRetVal;
         });
     }
 
     @Override
     public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
         // Intentionally NOOP
-
     }
 
     @Override
     public void removedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
-        if(!object.isDone() && object.cancel(false)) {
+        if (!object.isDone() && object.cancel(false)) {
             // We canceled adding event before it was processed
             // so it is safe to return
-            LOG.trace("Adding Bundle event for {} was cancelled. No additional work required.",bundle);
+            LOG.trace("Adding Bundle event for {} was cancelled. No additional work required.", bundle);
             return;
         }
         try {
-            LOG.trace("Invoking removedBundle event for {}",bundle);
+            LOG.trace("Invoking removedBundle event for {}", bundle);
             primaryTracker.removedBundle(bundle, event, object.get());
             forEachAdditionalBundle(tracker -> tracker.removedBundle(bundle, event, null));
-            LOG.trace("Removed bundle event for {} finished successfully.",bundle);
-        } catch (final Exception e) {
+            LOG.trace("Removed bundle event for {} finished successfully.", bundle);
+        } catch (final ExecutionException | InterruptedException e) {
             LOG.error("Failed to remove bundle {}", bundle, e);
         }
     }
@@ -120,5 +117,4 @@ public final class ExtensibleBundleTracker<T> extends BundleTracker<Future<T>> {
     private interface BundleStrategy {
         void execute(BundleTrackerCustomizer<?> tracker);
     }
-
 }
index 5e706250afe1c9d04df04d371d5d096eaca2f475..e89d6c87aa7aaa1cd89f0c6b832c5945630b280b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,8 +26,8 @@ import org.slf4j.LoggerFactory;
  * line should contain an implementation of ModuleFactory interface. Creates new
  * instance with default constructor and registers it into OSGi service
  * registry. There is no need for listening for implementing removedBundle as
- * the services are unregistered automatically.
- * Code based on http://www.toedter.com/blog/?p=236
+ * the services are unregistered automatically. Code based on
+ * http://www.toedter.com/blog/?p=236
  */
 public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boolean> {
     private final BlankTransactionServiceTracker blankTransactionServiceTracker;
@@ -40,8 +40,7 @@ public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boole
     @Override
     public Boolean addingBundle(final Bundle bundle, final BundleEvent event) {
         URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
-        LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
-                bundle, resource, event);
+        LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}", bundle, resource, event);
         if (resource != null) {
             try {
                 for (String factoryClassName : Resources.readLines(resource, StandardCharsets.UTF_8)) {
@@ -65,7 +64,7 @@ public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boole
 
     @Override
     public void removedBundle(final Bundle bundle, final BundleEvent event, final Boolean hasFactory) {
-        if(hasFactory) {
+        if (hasFactory) {
             // workaround for service tracker not getting removed service event
             blankTransactionServiceTracker.blankTransactionSync();
         }
@@ -79,31 +78,24 @@ public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boole
             Class<?> clazz = bundle.loadClass(factoryClassName);
             if (ModuleFactory.class.isAssignableFrom(clazz)) {
                 try {
-                    LOG.debug("Registering {} in bundle {}",
-                            clazz.getName(), bundle);
-                    return bundle.getBundleContext().registerService(
-                            ModuleFactory.class.getName(), clazz.newInstance(),
+                    LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
+                    return bundle.getBundleContext().registerService(ModuleFactory.class.getName(), clazz.newInstance(),
                             null);
                 } catch (final InstantiationException e) {
-                    errorMessage = logMessage(
-                            "Could not instantiate {} in bundle {}, reason {}",
-                            factoryClassName, bundle, e);
+                    errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", factoryClassName,
+                            bundle, e);
                     ex = e;
                 } catch (final IllegalAccessException e) {
-                    errorMessage = logMessage(
-                            "Illegal access during instantiation of class {} in bundle {}, reason {}",
+                    errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
                             factoryClassName, bundle, e);
                     ex = e;
                 }
             } else {
-                errorMessage = logMessage(
-                        "Class {} does not implement {} in bundle {}", clazz,
-                        ModuleFactory.class, bundle);
+                errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz, ModuleFactory.class,
+                        bundle);
             }
         } catch (final ClassNotFoundException e) {
-            errorMessage = logMessage(
-                    "Could not find class {} in bundle {}, reason {}",
-                    factoryClassName, bundle, e);
+            errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", factoryClassName, bundle, e);
             ex = e;
         }
 
index 472510f1bbbfc0d2fe040c72e982f7ee10a90bd9..6cf831510bf086ba9faba27c7f5441019ee94824 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -13,15 +13,18 @@ import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
 
 /**
- * Creates and initializes {@link BindingRuntimeContext}, which is used to resolve Identity classes from QName.
- * An instance of {@link BindingRuntimeContext} is available only after first schema context was successfully built.
+ * Creates and initializes {@link BindingRuntimeContext}, which is used to
+ * resolve Identity classes from QName. An instance of
+ * {@link BindingRuntimeContext} is available only after first schema context
+ * was successfully built.
  */
 // TODO move to yang runtime
 public class BindingContextProvider implements AutoCloseable {
 
     private BindingRuntimeContext current;
 
-    public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
+    public synchronized void update(final ClassLoadingStrategy classLoadingStrategy,
+            final SchemaContextProvider ctxProvider) {
         this.current = BindingRuntimeContext.create(classLoadingStrategy, ctxProvider.getSchemaContext());
     }
 
index 169d1e6ec84e8f9f27bc7bd13c120c1c3dbcdd39..71fcd58400cb64095579596e9d249ced694eef46 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,10 +26,11 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed into ModuleInfoRegistry
+ * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed
+ * into ModuleInfoRegistry.
  */
-public final class ModuleInfoBundleTracker implements AutoCloseable,
-        BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
+public final class ModuleInfoBundleTracker
+        implements AutoCloseable, BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
 
     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
 
@@ -72,6 +73,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(final Bundle bundle, final BundleEvent event) {
         URL resource = bundle.getEntry(YANG_MODULE_INFO_SERVICE_PATH);
         LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
@@ -87,7 +89,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
                 registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
             }
 
-            if(!starting) {
+            if (!starting) {
                 moduleInfoRegistry.updateService();
             }
         } catch (final IOException e) {
@@ -106,6 +108,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public void removedBundle(final Bundle bundle, final BundleEvent event,
             final Collection<ObjectRegistration<YangModuleInfo>> regs) {
         if (regs == null) {
@@ -127,7 +130,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
 
         if (!YangModelBindingProvider.class.isAssignableFrom(clazz)) {
             errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz,
-                YangModelBindingProvider.class, bundle);
+                    YangModelBindingProvider.class, bundle);
             throw new IllegalStateException(errorMessage);
         }
         final YangModelBindingProvider instance;
@@ -143,7 +146,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
             throw new IllegalStateException(errorMessage, e);
         }
 
-        try{
+        try {
             return instance.getModuleInfo();
         } catch (NoClassDefFoundError | ExceptionInInitializerError e) {
             throw new IllegalStateException("Error while executing getModuleInfo on " + instance, e);
@@ -154,8 +157,8 @@ public final class ModuleInfoBundleTracker implements AutoCloseable,
         try {
             return bundle.loadClass(moduleInfoClass);
         } catch (final ClassNotFoundException e) {
-            String errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", moduleInfoClass,
-                bundle, e);
+            String errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", moduleInfoClass, bundle,
+                    e);
             throw new IllegalStateException(errorMessage);
         }
     }
index fcde347881b41df99f32e5e94e23b5a548cc8fe0..9871a04f42ca0c243182a2150ad822583328c4e8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -20,15 +20,12 @@ import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 /**
- * Update SchemaContext service in Service Registry each time new YangModuleInfo is added or removed.
+ * Update SchemaContext service in Service Registry each time new YangModuleInfo
+ * is added or removed.
  */
 public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, AutoCloseable {
-    private static final Logger LOG = LoggerFactory.getLogger(RefreshingSCPModuleInfoRegistry.class);
-
     private final ModuleInfoRegistry moduleInfoRegistry;
     private final SchemaContextProvider schemaContextProvider;
     private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
@@ -38,39 +35,35 @@ public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, Auto
     private volatile ServiceRegistration<SchemaContextProvider> osgiReg;
 
     public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry,
-        final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat,
-        final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final BindingContextProvider bindingContextProvider,
-        final BundleContext bundleContext) {
+            final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat,
+            final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
+            final BindingContextProvider bindingContextProvider, final BundleContext bundleContext) {
 
         this.moduleInfoRegistry = moduleInfoRegistry;
         this.schemaContextProvider = schemaContextProvider;
         this.classLoadingStrat = classLoadingStrat;
         this.sourceProvider = sourceProvider;
         this.bindingContextProvider = bindingContextProvider;
-        this.osgiReg = bundleContext
-            .registerService(SchemaContextProvider.class, schemaContextProvider, new Hashtable<String, String>());
+        this.osgiReg = bundleContext.registerService(SchemaContextProvider.class, schemaContextProvider,
+                new Hashtable<String, String>());
     }
 
     public synchronized void updateService() {
         if (this.osgiReg != null) {
-            try {
-                this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider);
-
-                final Dictionary<String, Object> props = new Hashtable<>();
-                props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext());
-                props.put(SchemaSourceProvider.class.getName(), this.sourceProvider);
-                // send modifiedService event
-                this.osgiReg.setProperties(props);
-            } catch (final RuntimeException e) {
-                // The ModuleInfoBackedContext throws a RuntimeException if it can't create the schema context.
-                LOG.warn("Error updating the BindingContextProvider", e);
-            }
+            this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider);
+
+            final Dictionary<String, Object> props = new Hashtable<>();
+            props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext());
+            props.put(SchemaSourceProvider.class.getName(), this.sourceProvider);
+            // send modifiedService event
+            this.osgiReg.setProperties(props);
         }
     }
 
     @Override
     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
-        final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry.registerModuleInfo(yangModuleInfo);
+        final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry
+                .registerModuleInfo(yangModuleInfo);
         return new ObjectRegistrationWrapper(yangModuleInfoObjectRegistration);
     }
 
index 8538e3f84d62daf7e216352808743c1bfe2c78f9..059ba45ec9b79956fa4a3f07a0adad98888d6a3c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,8 +26,7 @@ public final class InterfacesHelper {
 
     public static Set<Class<?>> getAllInterfaces(Class<?> clazz) {
         if (clazz.isInterface()) {
-            throw new IllegalArgumentException(clazz
-                    + " should not be an interface");
+            throw new IllegalArgumentException(clazz + " should not be an interface");
         }
         // getInterfaces gets interfaces implemented directly by this class
         Set<Class<?>> toBeInspected = new HashSet<>();
@@ -48,7 +47,7 @@ public final class InterfacesHelper {
             Iterator<Class<?>> iterator = interfaces.iterator();
             Class<?> ifc = iterator.next();
             iterator.remove();
-            if (!ifc.isInterface())  {
+            if (!ifc.isInterface()) {
                 throw new IllegalArgumentException(ifc + " should be an interface");
             }
             interfaces.addAll(Arrays.asList(ifc.getInterfaces()));
@@ -59,9 +58,12 @@ public final class InterfacesHelper {
 
     /**
      * Get interfaces that this class is derived from that are JMX interfaces.
+     *
+     * @param configBeanClass
+     *            config bean class
+     * @return set containing classes
      */
-    public static Set<Class<?>> getMXInterfaces(
-            final Class<? extends Module> configBeanClass) {
+    public static Set<Class<?>> getMXInterfaces(final Class<? extends Module> configBeanClass) {
         Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
         Set<Class<?>> result = new HashSet<>();
         for (Class<?> clazz : allInterfaces) {
@@ -76,15 +78,17 @@ public final class InterfacesHelper {
      * Get all implemented interfaces that have
      * {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation}
      * annotation.
+     *
+     * @param configBeanClass
+     *            config bean class
+     * @return set containing classes
      */
-    public static Set<Class<?>> getServiceInterfaces(
-            final Class<? extends Module> configBeanClass) {
+    public static Set<Class<?>> getServiceInterfaces(final Class<? extends Module> configBeanClass) {
         Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
         Set<Class<?>> result = new HashSet<>();
         for (Class<?> clazz : allInterfaces) {
             if (AbstractServiceInterface.class.isAssignableFrom(clazz)) {
-                ServiceInterfaceAnnotation annotation = clazz
-                        .getAnnotation(ServiceInterfaceAnnotation.class);
+                ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
                 if (annotation != null) {
                     result.add(clazz);
                 }
@@ -93,52 +97,58 @@ public final class InterfacesHelper {
         return result;
     }
 
-    public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(final Class<? extends Module> configBeanClass) {
+    public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(
+            final Class<? extends Module> configBeanClass) {
 
         Set<Class<? extends AbstractServiceInterface>> foundGeneratedSIClasses = new HashSet<>();
         for (Class<?> clazz : getAllInterfaces(configBeanClass)) {
-            if (AbstractServiceInterface.class.isAssignableFrom(clazz) && !AbstractServiceInterface.class.equals(clazz)) {
+            if (AbstractServiceInterface.class.isAssignableFrom(clazz)
+                    && !AbstractServiceInterface.class.equals(clazz)) {
                 foundGeneratedSIClasses.add((Class<? extends AbstractServiceInterface>) clazz);
             }
         }
         return getAllAbstractServiceInterfaceClasses(foundGeneratedSIClasses);
     }
 
-
     /**
      * Get OSGi registration types under which config bean instance should be
      * registered. This is specified in
      * {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation#osgiRegistrationType()}
+     *
+     * @param configBeanClass config bean class
+     * @return set of classes
      */
-    public static Set<Class<?>> getOsgiRegistrationTypes(
-            final Class<? extends Module> configBeanClass) {
+    public static Set<Class<?>> getOsgiRegistrationTypes(final Class<? extends Module> configBeanClass) {
         Set<Class<?>> serviceInterfaces = getServiceInterfaces(configBeanClass);
         Set<Class<?>> result = new HashSet<>();
         for (Class<?> clazz : serviceInterfaces) {
-            ServiceInterfaceAnnotation annotation = clazz
-                    .getAnnotation(ServiceInterfaceAnnotation.class);
+            ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
             result.add(annotation.osgiRegistrationType());
         }
         return result;
     }
 
     public static Set<String> getQNames(final Set<ServiceInterfaceAnnotation> siAnnotations) {
-        Set<String> qNames = new HashSet<>();
-        for (ServiceInterfaceAnnotation sia: siAnnotations) {
-            qNames.add(sia.value());
+        Set<String> names = new HashSet<>();
+        for (ServiceInterfaceAnnotation sia : siAnnotations) {
+            names.add(sia.value());
         }
-        return ImmutableSet.copyOf(qNames);
+        return ImmutableSet.copyOf(names);
     }
 
     public static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final ModuleFactory factory) {
-        Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections.unmodifiableSet(factory.getImplementedServiceIntefaces());
+        Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections
+                .unmodifiableSet(factory.getImplementedServiceIntefaces());
         return getServiceInterfaceAnnotations(implementedServiceIntefaces);
     }
 
-    private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
-        Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(implementedServiceIntefaces);
+    private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(
+            final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
+        Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(
+                implementedServiceIntefaces);
         Set<ServiceInterfaceAnnotation> result = new HashSet<>();
-        // SIs can form hierarchies, inspect superclass until it does not extend AbstractSI
+        // SIs can form hierarchies, inspect superclass until it does not extend
+        // AbstractSI
         for (Class<?> clazz : inspected) {
             ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
             if (annotation != null) {
@@ -153,12 +163,10 @@ public final class InterfacesHelper {
 
         Set<Class<?>> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs);
         Set<Class<? extends AbstractServiceInterface>> result = new HashSet<>();
-        for(Class<?> ifc: allInterfaces){
-            if (AbstractServiceInterface.class.isAssignableFrom(ifc) &&
-                    !ifc.equals(AbstractServiceInterface.class)) {
+        for (Class<?> ifc : allInterfaces) {
+            if (AbstractServiceInterface.class.isAssignableFrom(ifc) && !ifc.equals(AbstractServiceInterface.class)) {
                 result.add((Class<? extends AbstractServiceInterface>) ifc);
             }
-
         }
         return result;
     }
index 1fa97acd2fe403f0dc13228b3acdab180d6a2f4e..e1c73df41369c7647543474a7cefbbf76ad4b436 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -16,7 +16,7 @@ import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.osgi.framework.BundleContext;
 
-public class ModuleQNameUtil {
+public final class ModuleQNameUtil {
 
     private ModuleQNameUtil() {
     }
@@ -29,7 +29,7 @@ public class ModuleQNameUtil {
                 throw new IllegalArgumentException("Unexpected interface " + inspected);
             }
             ModuleQName annotation = null;
-            while(annotation == null && inspected != null) {
+            while (annotation == null && inspected != null) {
                 annotation = inspected.getAnnotation(ModuleQName.class);
                 inspected = inspected.getSuperclass();
             }
@@ -39,5 +39,4 @@ public class ModuleQNameUtil {
         }
         return result;
     }
-
 }
index 607cf49db9c02cf770a747a839cce715a52ade5a..2642e560224c4697c93461c5a91bbc9cd422572e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.config.manager.impl.util;
 
 import static com.google.common.base.Preconditions.checkNotNull;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.ListIterator;
@@ -26,7 +27,8 @@ public class OsgiRegistrationUtil {
     }
 
     @SafeVarargs
-    public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class<? super T> ... interfaces) {
+    public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service,
+            final Class<? super T>... interfaces) {
         checkNotNull(service);
         checkNotNull(interfaces);
         List<AutoCloseable> autoCloseableList = new ArrayList<>();
@@ -52,9 +54,7 @@ public class OsgiRegistrationUtil {
         return serviceTracker::close;
     }
 
-    /**
-     * Close list of auto closeables in reverse order
-     */
+    @SuppressWarnings("IllegalCatch")
     public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
         checkNotNull(list);
 
index 5fc5884531413de103d51ea32d4db8f4166c8a15..55e8bb2a66f5939344ac4e39588b3670671a4866 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -24,31 +24,26 @@ import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class ConfigRegistryImplTest extends
-        AbstractLockedPlatformMBeanServerTest {
-    private static final Logger LOG = LoggerFactory
-            .getLogger(ConfigRegistryImplTest.class);
+public class ConfigRegistryImplTest extends AbstractLockedPlatformMBeanServerTest {
+    private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImplTest.class);
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testFailOnTwoFactoriesExportingSameImpl() {
         ModuleFactory factory = new TestingFixedThreadPoolModuleFactory();
         BundleContext context = mock(BundleContext.class);
         ConfigRegistryImpl configRegistry = null;
         try {
-            ModuleFactoriesResolver resolver = new HardcodedModuleFactoriesResolver(mock(BundleContext.class),
-                    factory, factory);
+            ModuleFactoriesResolver resolver = new HardcodedModuleFactoriesResolver(mock(BundleContext.class), factory,
+                    factory);
 
-            configRegistry = new ConfigRegistryImpl(resolver,
-                    ManagementFactory.getPlatformMBeanServer(), null);
+            configRegistry = new ConfigRegistryImpl(resolver, ManagementFactory.getPlatformMBeanServer(), null);
 
             configRegistry.beginConfig();
             fail();
         } catch (final IllegalArgumentException e) {
-            assertTrue(
-                    e.getMessage(),
-                    e.getMessage()
-                            .startsWith("Module name is not unique. Found two conflicting factories with same name " +
-                                    "'fixed':"));
+            assertTrue(e.getMessage(), e.getMessage().startsWith(
+                    "Module name is not unique. Found two conflicting factories with same name " + "'fixed':"));
             verifyZeroInteractions(context);
         } finally {
             try {
@@ -59,5 +54,4 @@ public class ConfigRegistryImplTest extends
             }
         }
     }
-
 }
index deb202cf002c1bee08aeb5d8de099cbc73947113..c03c226978f054b4ff3df9cd98b9b291ed4bc9af 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -57,7 +57,8 @@ import org.osgi.framework.ServiceRegistration;
  * needs to subclass this test.
  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
  * registered to platform MBean Server using
- * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
+ * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller
+ * .config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
  * typically during setting up the each test.
  */
 public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServerTest {
@@ -78,10 +79,13 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
     }
 
     // Default handler for OSGi service registration
-    protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
+    protected static class RecordingBundleContextServiceRegistrationHandler
+            implements BundleContextServiceRegistrationHandler {
         private final List<RegistrationHolder> registrations = new LinkedList<>();
+
         @Override
-        public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance, final Dictionary<String, ?> props) {
+        public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance,
+                final Dictionary<String, ?> props) {
             this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
         }
 
@@ -102,7 +106,8 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
         }
     }
 
-    protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(final Class<?> serviceType) {
+    protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(
+            final Class<?> serviceType) {
         return this.currentBundleContextServiceRegistrationHandler;
     }
 
@@ -116,17 +121,19 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
 
         this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
 
-        this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator, new BindingContextProvider() {
-            @Override
-            public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
-                // NOOP
-            }
+        this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator,
+                new BindingContextProvider() {
+                    @Override
+                    public synchronized void update(final ClassLoadingStrategy classLoadingStrategy,
+                            final SchemaContextProvider ctxProvider) {
+                        // NOOP
+                    }
 
-            @Override
-            public synchronized BindingRuntimeContext getBindingContext() {
-                return getBindingRuntimeContext();
-            }
-        });
+                    @Override
+                    public synchronized BindingRuntimeContext getBindingContext() {
+                        return getBindingRuntimeContext();
+                    }
+                });
         this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
 
         try {
@@ -142,8 +149,10 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
     private void initBundleContext() {
         doNothing().when(this.mockedServiceRegistration).unregister();
         final RegisterServiceAnswer answer = new RegisterServiceAnswer();
-        doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
-        doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(), Matchers.<Dictionary<String, ?>>any());
+        doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(),
+                Matchers.<Dictionary<String, ?>>any());
+        doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(),
+                Matchers.<Dictionary<String, ?>>any());
     }
 
     @After
@@ -156,12 +165,11 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
     }
 
     /**
-     * Can be called in @After of tests if some other cleanup is needed that
-     * would be discarded by closing config beans in this method
+     * Can be called in @After of tests if some other cleanup is needed that would
+     * be discarded by closing config beans in this method.
      */
     protected void destroyAllConfigBeans() throws Exception {
-        final ConfigTransactionJMXClient transaction = this.configRegistryClient
-                .createTransaction();
+        final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
         Set<ObjectName> all = transaction.lookupConfigBeans();
         // workaround for getting same Module more times
         while (all.size() > 0) {
@@ -175,23 +183,23 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
             final int expectedRecreatedInstances, final int expectedReusedInstances) {
         assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
         assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
-            status.getRecreatedInstances().size());
+                status.getRecreatedInstances().size());
         assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
-            status.getReusedInstances().size());
+                status.getReusedInstances().size());
     }
 
-
-    protected void assertBeanCount(final int i, final String configMXBeanName) {
-        assertEquals(i, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
+    protected void assertBeanCount(final int index, final String configMXBeanName) {
+        assertEquals(index, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
     }
 
     /**
+     * Empty constructor.
      *
      * @param configBeanClass
-     *            Empty constructor class of config bean to be instantiated
-     *            whenever create
-     * @param implementationName
-     * @return
+     *            Empty constructor class of config bean to be instantiated whenever
+     *            create
+     * @param implementationName name
+     * @return factory
      */
     protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
             final String implementationName) {
@@ -216,8 +224,7 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
             final Object serviceTypeRaw = args[0];
             final Object serviceInstance = args[1];
             @SuppressWarnings("unchecked")
-            final
-            Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
+            final Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
 
             if (serviceTypeRaw instanceof Class) {
                 final Class<?> serviceType = (Class<?>) serviceTypeRaw;
@@ -229,23 +236,27 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
             } else if (serviceTypeRaw instanceof String) {
                 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
             } else {
-                throw new IllegalStateException("Not handling service registration of type, Unknown type" +  serviceTypeRaw);
+                throw new IllegalStateException(
+                        "Not handling service registration of type, Unknown type" + serviceTypeRaw);
             }
 
             return AbstractConfigTest.this.mockedServiceRegistration;
         }
 
-        public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary<String, ?> props) {
+        public void invokeServiceHandler(final Object serviceInstance, final String className,
+                final Dictionary<String, ?> props) {
             try {
                 final Class<?> serviceType = Class.forName(className);
                 invokeServiceHandler(serviceInstance, serviceType, props);
             } catch (final ClassNotFoundException e) {
-                throw new IllegalStateException("Not handling service registration of type " +  className, e);
+                throw new IllegalStateException("Not handling service registration of type " + className, e);
             }
         }
 
-        private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType, final Dictionary<String, ?> props) {
-            final BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
+        private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType,
+                final Dictionary<String, ?> props) {
+            final BundleContextServiceRegistrationHandler serviceRegistrationHandler =
+                    getBundleContextServiceRegistrationHandler(serviceType);
 
             if (serviceRegistrationHandler != null) {
                 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
@@ -254,32 +265,34 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ
     }
 
     /**
-     * Expand inner exception wrapped by JMX
+     * Expand inner exception wrapped by JMX.
      *
-     * @param innerObject jmx proxy which will be wrapped and returned
+     * @param innerObject
+     *            jmx proxy which will be wrapped and returned
      */
     protected <T> T rethrowCause(final T innerObject) {
         @SuppressWarnings("unchecked")
-        final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
+        final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
                 innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
+                try {
+                    return method.invoke(innerObject, args);
+                } catch (final InvocationTargetException e) {
                     try {
-                        return method.invoke(innerObject, args);
-                    } catch (final InvocationTargetException e) {
-                        try {
-                            throw e.getTargetException();
-                        } catch (final RuntimeMBeanException e2) {
-                            throw e2.getTargetException();
-                        }
+                        throw e.getTargetException();
+                    } catch (final RuntimeMBeanException e2) {
+                        throw e2.getTargetException();
                     }
                 }
-        );
+            });
         return proxy;
     }
 
     /**
-     * removes contents of the directory
-     * @param dir to be cleaned
-     * @throws IOException
+     * removes contents of the directory.
+     *
+     * @param dir
+     *            to be cleaned
+     * @throws IOException IO exception
      */
     protected void cleanDirectory(final File dir) throws IOException {
         if (!dir.isDirectory()) {
index fbb3d555ccfbf05b68871a97a3dadc780af16e2c..ced512203e3a7b967fdbad0903cf0e5100c832db 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -17,26 +17,23 @@ import org.junit.Before;
  * Each test that works with platform MBeanServer should extend this class.
  */
 public abstract class AbstractLockedPlatformMBeanServerTest {
-    private static final ReentrantLock lock = new ReentrantLock();
+    private static final ReentrantLock LOCK = new ReentrantLock();
     protected static MBeanServer platformMBeanServer = ManagementFactory
             .getPlatformMBeanServer();
 
     @Before
     public void acquireLock() {
-        lock.lock();
+        LOCK.lock();
     }
 
     @After
     public void unlock() {
-        lock.unlock();
+        LOCK.unlock();
     }
 
     public static class SimpleBean implements SimpleBeanMBean {
-
     }
 
     public interface SimpleBeanMBean {
-
     }
-
 }
index 7681b00d90a509a0710eeda2283e0807aa4e080c..1acf6b2fee0ab2b01f855fdbcca322d67c13647c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -18,23 +18,24 @@ public abstract class AbstractMockedModule implements Module {
 
     protected abstract AutoCloseable prepareMockedInstance() throws Exception;
 
+    @SuppressWarnings("IllegalCatch")
     public AbstractMockedModule(final DynamicMBeanWithInstance old, final ModuleIdentifier id) {
-        if(old!=null)
+        if (old != null) {
             instance = old.getInstance();
-        else
+        } else {
             try {
                 instance = prepareMockedInstance();
             } catch (final Exception e) {
                 throw new RuntimeException(e);
             }
+        }
 
-        this.id = id==null ? new ModuleIdentifier(getClass().getCanonicalName(), "mock") : id;
+        this.id = id == null ? new ModuleIdentifier(getClass().getCanonicalName(), "mock") : id;
     }
 
-
     @Override
     public boolean canReuse(final Module oldModule) {
-        return instance!=null;
+        return instance != null;
     }
 
     @Override
@@ -50,5 +51,4 @@ public abstract class AbstractMockedModule implements Module {
     public ModuleIdentifier getIdentifier() {
         return id;
     }
-
 }
index 451d85f7805030ee363554ea3b007e455914133c..93661699c4712debfc4cba9d4306e4a8e06e2913 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,9 +26,9 @@ import org.osgi.framework.BundleContext;
 
 /**
  * Creates new modules by reflection. Provided class must have this constructor:
- * ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class).
- * When reconfiguring, both parameters will be non null. When creating new
- * instance first parameter will be null.
+ * ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class). When
+ * reconfiguring, both parameters will be non null. When creating new instance
+ * first parameter will be null.
  *
  */
 public class ClassBasedModuleFactory implements ModuleFactory {
@@ -36,14 +36,15 @@ public class ClassBasedModuleFactory implements ModuleFactory {
     private final Class<? extends Module> configBeanClass;
 
     /**
+     * Module factory constructor.
+     *
      * @param implementationName
+     *            name of the implementation
      * @param configBeanClass
-     *            class that will be instantiated when createModule is called.
-     *            This class must implement Module interface and all exported
-     *            interfaces.
+     *            class that will be instantiated when createModule is called. This
+     *            class must implement Module interface and all exported interfaces.
      */
-    public ClassBasedModuleFactory(final String implementationName,
-            final Class<? extends Module> configBeanClass) {
+    public ClassBasedModuleFactory(final String implementationName, final Class<? extends Module> configBeanClass) {
         this.implementationName = implementationName;
         this.configBeanClass = configBeanClass;
     }
@@ -54,38 +55,39 @@ public class ClassBasedModuleFactory implements ModuleFactory {
     }
 
     @Override
-    public Module createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
-            throws Exception {
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
         Preconditions.checkNotNull(old);
         return constructModule(instanceName, dependencyResolver, old);
     }
 
-    private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old) throws InstantiationException, IllegalAccessException, InvocationTargetException {
+    @Override
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final BundleContext bundleContext) {
+        try {
+            return constructModule(instanceName, dependencyResolver, null);
+        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final DynamicMBeanWithInstance old)
+            throws InstantiationException, IllegalAccessException, InvocationTargetException {
         Preconditions.checkNotNull(dependencyResolver);
         ModuleIdentifier moduleIdentifier = new ModuleIdentifier(implementationName, instanceName);
         Constructor<? extends Module> declaredConstructor;
         try {
-            declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class, ModuleIdentifier.class);
+            declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class,
+                    ModuleIdentifier.class);
         } catch (final NoSuchMethodException e) {
             throw new IllegalStateException(
-                    "Did not find constructor with parameters (DynamicMBeanWithInstance) in "
-                            + configBeanClass, e);
+                    "Did not find constructor with parameters (DynamicMBeanWithInstance) in " + configBeanClass, e);
         }
         Preconditions.checkState(declaredConstructor != null);
         return declaredConstructor.newInstance(old, moduleIdentifier);
     }
 
-    @Override
-    public Module createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        try {
-            return constructModule(instanceName, dependencyResolver, null);
-        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
     @Override
     public boolean isModuleImplementingServiceInterface(
             final Class<? extends AbstractServiceInterface> serviceInterface) {
@@ -104,7 +106,8 @@ public class ClassBasedModuleFactory implements ModuleFactory {
     }
 
     @Override
-    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+            final BundleContext bundleContext) {
         return new HashSet<>();
     }
 
index eabf8ec52041b4d7c5b038aa0f2e2d95d3e27de0..8368a2723f9f422fcf95fd4edfc0a84d39e3aea7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -29,75 +29,65 @@ import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
 import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean;
 
-public class ConfigRegistryImplLookupTest extends
-        AbstractLockedPlatformMBeanServerTest {
+public class ConfigRegistryImplLookupTest extends AbstractLockedPlatformMBeanServerTest {
 
     private ConfigRegistryImpl configRegistryImpl;
     private BaseJMXRegistrator baseJMXRegistrator;
 
-    private static final String moduleNameA = "moduleA";
-    private static final String moduleNameB = "moduleB";
+    private static final String MODULE_NAMEA = "moduleA";
+    private static final String MODULE_NAMEB = "moduleB";
 
-    private static final String instanceNameA = "instA";
-    private static final String instanceNameB = "instB";
-    private static final String instanceNameC = "instC";
+    private static final String INSTANCE_NAMEA = "instA";
+    private static final String INSTANCE_NAMEB = "instB";
+    private static final String INSTANCE_NAMEC = "instC";
 
-    private static final ObjectName name1 = ObjectNameUtil
-            .createReadOnlyModuleON(moduleNameA, instanceNameA);
-    private static final ObjectName name2 = ObjectNameUtil
-            .createReadOnlyModuleON(moduleNameA, instanceNameB);
-    private static final ObjectName name3 = ObjectNameUtil
-            .createReadOnlyModuleON(moduleNameA, instanceNameC);
-    private static final ObjectName name4 = ObjectNameUtil
-            .createReadOnlyModuleON(moduleNameB, instanceNameA);
+    private static final ObjectName NAME1 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEA);
+    private static final ObjectName NAME2 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEB);
+    private static final ObjectName NAME3 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEC);
+    private static final ObjectName NAME4 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEB, INSTANCE_NAMEA);
 
-    private static final ObjectName name5 = ObjectNameUtil
-            .createRuntimeBeanName(moduleNameA, instanceNameA, Collections.<String, String>emptyMap());
-    private static final ObjectName name6 = ObjectNameUtil
-            .createRuntimeBeanName(moduleNameA, instanceNameB, Collections.<String, String>emptyMap());
-    private static final ObjectName name8 = ObjectNameUtil
-            .createRuntimeBeanName(moduleNameB, instanceNameA, Collections.<String, String>emptyMap());
+    private static final ObjectName NAME5 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEA,
+            Collections.<String, String>emptyMap());
+    private static final ObjectName NAME6 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEB,
+            Collections.<String, String>emptyMap());
+    private static final ObjectName NAME8 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEB, INSTANCE_NAMEA,
+            Collections.<String, String>emptyMap());
 
-    private static final ObjectName name9 = ObjectNameUtil
-            .createTransactionModuleON("transaction", moduleNameA, instanceNameA);
+    private static final ObjectName NAME9 = ObjectNameUtil.createTransactionModuleON("transaction", MODULE_NAMEA,
+            INSTANCE_NAMEA);
 
     @Before
     public void setUp() throws Exception {
-        configRegistryImpl = new ConfigRegistryImpl(null,
-                ManagementFactory.getPlatformMBeanServer(), null);
-        Field field = configRegistryImpl.getClass().getDeclaredField(
-                "baseJMXRegistrator");
+        configRegistryImpl = new ConfigRegistryImpl(null, ManagementFactory.getPlatformMBeanServer(), null);
+        Field field = configRegistryImpl.getClass().getDeclaredField("baseJMXRegistrator");
         field.setAccessible(true);
         baseJMXRegistrator = (BaseJMXRegistrator) field.get(configRegistryImpl);
 
-        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name1);
-        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name2);
-        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name3);
-        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name4);
+        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME1);
+        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME2);
+        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME3);
+        registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME4);
 
-        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name5);
-        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name6);
-        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name8);
+        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME5);
+        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME6);
+        registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME8);
 
-        baseJMXRegistrator.createTransactionJMXRegistrator("transaction")
-                .createTransactionModuleJMXRegistrator()
-                .registerMBean(new TestingRuntimeBean(), name9);
+        baseJMXRegistrator.createTransactionJMXRegistrator("transaction").createTransactionModuleJMXRegistrator()
+                .registerMBean(new TestingRuntimeBean(), NAME9);
 
     }
 
     private static void registerModuleBean(final TestingRuntimeBean testingRuntimeBean,
             final BaseJMXRegistrator baseJMXRegistrator, final ObjectName objectName)
             throws InstanceAlreadyExistsException {
-        baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(
-                testingRuntimeBean, objectName);
+        baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(testingRuntimeBean, objectName);
     }
 
     private static void registerRuntimeBean(final RuntimeBean object, final BaseJMXRegistrator baseJMXRegistrator,
             final ObjectName runtimeON) throws InstanceAlreadyExistsException {
         String factoryName = ObjectNameUtil.getFactoryName(runtimeON);
         String instanceName = ObjectNameUtil.getInstanceName(runtimeON);
-        Map<String, String> properties = ObjectNameUtil
-                .getAdditionalPropertiesOfRuntimeBeanName(runtimeON);
+        Map<String, String> properties = ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(runtimeON);
 
         RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
                 .createRuntimeBeanRegistrator(new ModuleIdentifier(factoryName, instanceName));
@@ -115,39 +105,34 @@ public class ConfigRegistryImplLookupTest extends
     @Test
     public void testLookupConfigBeans() throws Exception {
         Set<ObjectName> beans = configRegistryImpl.lookupConfigBeans();
-        assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans);
+        assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
         beans = configRegistryImpl.lookupConfigBeans();
-        assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans);
+        assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
     }
 
     @Test
     public void testLookupConfigBeanWithModuleName() throws Exception {
-        Set<ObjectName> bean = configRegistryImpl
-                .lookupConfigBeans(moduleNameA);
-        assertEquals(Sets.newHashSet(name1, name2, name3), bean);
+        Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA);
+        assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), bean);
     }
 
     @Test
-    public void testLookupConfigBeanWithModuleNameAndInstanceName()
-            throws Exception {
-        Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(
-                moduleNameA, instanceNameA);
-        assertEquals(Sets.newHashSet(name1), bean);
+    public void testLookupConfigBeanWithModuleNameAndInstanceName() throws Exception {
+        Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA, INSTANCE_NAMEA);
+        assertEquals(Sets.newHashSet(NAME1), bean);
     }
 
     @Test
     public void testLookupRuntimeBeans() throws Exception {
         Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans();
-        assertEquals(Sets.newHashSet(name5, name6, name8), beans);
+        assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
         beans = configRegistryImpl.lookupRuntimeBeans(null, null);
-        assertEquals(Sets.newHashSet(name5, name6, name8), beans);
+        assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
     }
 
     @Test
     public void testLookupRuntimeBeansWithIFcNameAndImplName() throws Exception {
-        Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans(
-                moduleNameA, instanceNameA);
-        assertEquals(Sets.newHashSet(name5), beans);
+        Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans(MODULE_NAMEA, INSTANCE_NAMEA);
+        assertEquals(Sets.newHashSet(NAME5), beans);
     }
-
 }
index 9263e42948959ae9778dbebe77624915c75a54cc..82666e8e6a8d4a3b76d4dce63f78623447a79df3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -28,63 +28,58 @@ import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRunti
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.osgi.framework.BundleContext;
 
-public class ConfigTransactionControllerImplTest extends
-        AbstractLockedPlatformMBeanServerTest {
+public class ConfigTransactionControllerImplTest extends AbstractLockedPlatformMBeanServerTest {
 
     private BaseJMXRegistrator baseJMXRegistrator;
 
     private ConfigTransactionControllerImpl testedTxController;
     private MBeanServer transactionsMBeanServer;
 
-    private static final String transactionName123 = "testTX1";
-    private static final String transactionName4 = "testTX2";
+    private static final String TRANSACTION_NAME123 = "testTX1";
+    private static final String TRANSACTION_NAME4 = "testTX2";
 
-    private static final String moduleName124 = "module124";
-    private static final String moduleName3 = "module3";
+    private static final String MODULE_NAME124 = "module124";
+    private static final String MODULE_NAME3 = "module3";
 
-    private static final String instanceName134 = "instA";
-    private static final String instanceName2 = "instB";
+    private static final String INSTANCE_NAME134 = "instA";
+    private static final String INSTANCE_NAME2 = "instB";
 
-    private static final ObjectName name1 = ObjectNameUtil
-            .createTransactionModuleON(transactionName123, moduleName124, instanceName134);
-    private static final ObjectName name2 = ObjectNameUtil
-            .createTransactionModuleON(transactionName123, moduleName124, instanceName2);
-    private static final ObjectName name3 = ObjectNameUtil
-            .createTransactionModuleON(transactionName123, moduleName3, instanceName134);
-    private static final ObjectName name4 = ObjectNameUtil
-            .createTransactionModuleON(transactionName4, moduleName124, instanceName134);
+    private static final ObjectName NAME1 =
+            ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME124, INSTANCE_NAME134);
+    private static final ObjectName NAME2 =
+            ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123,
+            MODULE_NAME124, INSTANCE_NAME2);
+    private static final ObjectName NAME3 =
+            ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME3, INSTANCE_NAME134);
+    private static final ObjectName NAME4 =
+            ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME4, MODULE_NAME124, INSTANCE_NAME134);
 
     @Before
     public void setUp() throws Exception {
-        baseJMXRegistrator = new BaseJMXRegistrator(
-                ManagementFactory.getPlatformMBeanServer());
+        baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
         transactionsMBeanServer = MBeanServerFactory.createMBeanServer();
         Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories = new HashMap<>();
 
         ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
-            new TransactionIdentifier(transactionName123), () ->
-            baseJMXRegistrator.createTransactionJMXRegistrator(transactionName123), currentlyRegisteredFactories);
+                new TransactionIdentifier(TRANSACTION_NAME123),
+            () -> baseJMXRegistrator.createTransactionJMXRegistrator(TRANSACTION_NAME123),
+            currentlyRegisteredFactories);
 
-        SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
-                ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(), txLookupRegistry, currentlyRegisteredFactories);
+        SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
+                .createSRWritableRegistry(ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(),
+                        txLookupRegistry, currentlyRegisteredFactories);
 
-
-        testedTxController = new ConfigTransactionControllerImpl(
-                txLookupRegistry, 1, null, 1,
-                currentlyRegisteredFactories, transactionsMBeanServer,
-                ManagementFactory.getPlatformMBeanServer(), false, writableRegistry);
+        testedTxController = new ConfigTransactionControllerImpl(txLookupRegistry, 1, null, 1,
+                currentlyRegisteredFactories, transactionsMBeanServer, ManagementFactory.getPlatformMBeanServer(),
+                false, writableRegistry);
         TransactionModuleJMXRegistrator transactionModuleJMXRegistrator123 = testedTxController
                 .getTxModuleJMXRegistrator();
-        transactionModuleJMXRegistrator123.registerMBean(
-                new TestingRuntimeBean(), name1);
-        transactionModuleJMXRegistrator123.registerMBean(
-                new TestingRuntimeBean(), name2);
-        transactionModuleJMXRegistrator123.registerMBean(
-                new TestingRuntimeBean(), name3);
+        transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME1);
+        transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME2);
+        transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME3);
         TransactionJMXRegistrator jmxRegistrator4 = baseJMXRegistrator
-                .createTransactionJMXRegistrator(transactionName4);
-        jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(
-                new TestingRuntimeBean(), name4);
+                .createTransactionJMXRegistrator(TRANSACTION_NAME4);
+        jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(new TestingRuntimeBean(), NAME4);
     }
 
     @After
@@ -94,25 +89,23 @@ public class ConfigTransactionControllerImplTest extends
     }
 
     /**
-     * Tests if lookup method returns all beans with defined transaction name
+     * Tests if lookup method returns all beans with defined transaction name.
      */
     @Test
     public void testLookupConfigBeans() {
         Set<ObjectName> beans = testedTxController.lookupConfigBeans();
-        assertEquals(Sets.newHashSet(name1, name2, name3), beans);
+        assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), beans);
     }
 
     @Test
     public void testLookupConfigBeansWithModuleName() {
-        Set<ObjectName> beans = testedTxController
-                .lookupConfigBeans(moduleName124);
-        assertEquals(Sets.newHashSet(name1, name2), beans);
+        Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124);
+        assertEquals(Sets.newHashSet(NAME1, NAME2), beans);
     }
 
     @Test
     public void lookupConfigBeansWithModuleNameAndImplName() throws Exception {
-        Set<ObjectName> beans = testedTxController.lookupConfigBeans(
-                moduleName124, instanceName134);
-        assertEquals(Sets.newHashSet(name1), beans);
+        Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124, INSTANCE_NAME134);
+        assertEquals(Sets.newHashSet(NAME1), beans);
     }
-}
\ No newline at end of file
+}
index cc4d3cad3602032d59ba001c3e32131e39690a74..ede2a805a8c0a2814fd1d027bd276a645503a4ac 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -32,7 +32,7 @@ public class ConfigTransactionManagerImplTest extends
         try {
             configRegistryJMXRegistrator.registerToJMX(mockedRegistry);
             fail();
-        } catch (final Exception e) {
+        } catch (final InstanceAlreadyExistsException e) {
             assertTrue(e instanceof InstanceAlreadyExistsException);
         }
     }
@@ -49,5 +49,4 @@ public class ConfigTransactionManagerImplTest extends
                 .createTransaction();
         transaction.commit();
     }
-
 }
index 9b9a92270a37354af1b5f7defa414ec245b18487..5ab15570230e58e085db9d5615b31b2b07c058c0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -38,14 +38,11 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 
 public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
 
-
     @Before
     public void setUp() {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(
-                mockedContext,
-                new TestingFixedThreadPoolModuleFactory(),
-                new TestingParallelAPSPModuleFactory(),
-                new TestingScheduledThreadPoolModuleFactory()));
+        super.initConfigTransactionManagerImpl(
+                new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory(),
+                        new TestingParallelAPSPModuleFactory(), new TestingScheduledThreadPoolModuleFactory()));
     }
 
     @Override
@@ -57,19 +54,19 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
     public void test() throws Exception {
         ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
         // create fixed1
-        int fixedNrOfThreads = 20, scheduledNrOfThreads = 30;
+        int fixedNrOfThreads = 20;
+        int scheduledNrOfThreads = 30;
 
         ObjectName fixedTPTransactionON = transaction1.createModule(getThreadPoolImplementationName(), fixed1);
         platformMBeanServer.setAttribute(fixedTPTransactionON, new Attribute("ThreadCount", fixedNrOfThreads));
 
-        ObjectName scheduledTPTransactionON = transaction1.createModule(
-                TestingScheduledThreadPoolModuleFactory.NAME, "scheduled1");
-        platformMBeanServer.setAttribute(scheduledTPTransactionON, new Attribute("ThreadCount",
-                scheduledNrOfThreads));
+        ObjectName scheduledTPTransactionON = transaction1.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
+                "scheduled1");
+        platformMBeanServer.setAttribute(scheduledTPTransactionON, new Attribute("ThreadCount", scheduledNrOfThreads));
 
         String refName = "ref";
-        ObjectName serviceReference = transaction1.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName,
-                fixedTPTransactionON);
+        ObjectName serviceReference = transaction1.saveServiceReference(TestingThreadPoolServiceInterface.QNAME,
+                refName, fixedTPTransactionON);
         // create apsp-parallel
         createParallelAPSP(transaction1, serviceReference);
         transaction1.commit();
@@ -81,11 +78,12 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
         checkApspThreadCount(fixedNrOfThreads);
         // check OSGi SR
         List<RegistrationHolder> registrations =
-                ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler).getRegistrations();
+                ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler)
+                .getRegistrations();
         assertEquals(1, registrations.size());
         RegistrationHolder record = registrations.get(0);
         assertEquals(TestingThreadPoolIfc.class, record.clazz);
-        assertEquals(ImmutableMap.of("name","ref"), record.props);
+        assertEquals(ImmutableMap.of("name", "ref"), record.props);
 
         // switch reference to scheduled
         ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
@@ -95,21 +93,22 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
         // check scheduled is used
         checkApspThreadCount(scheduledNrOfThreads);
         // check that dummy MXBean points to scheduled
-        assertEquals(withoutTransactionName(scheduledTPTransactionON), serviceReferenceMXBean.getCurrentImplementation());
+        assertEquals(withoutTransactionName(scheduledTPTransactionON),
+                serviceReferenceMXBean.getCurrentImplementation());
 
         // empty transaction
         configRegistryClient.createTransaction().commit();
 
         // get service mapping
-        Map<String,Map<String,ObjectName>> serviceMapping = configRegistryClient.getServiceMapping();
-        Map<String,Map<String,ObjectName>> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME,
-                (Map<String, ObjectName>)ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON)));
+        Map<String, Map<String, ObjectName>> serviceMapping = configRegistryClient.getServiceMapping();
+        Map<String, Map<String, ObjectName>> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME,
+                (Map<String, ObjectName>) ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON)));
         assertEquals(expectedMapping, serviceMapping);
 
         // destroy all
         ConfigTransactionJMXClient transaction4 = configRegistryClient.createTransaction();
         Set<ObjectName> objectNames = transaction4.lookupConfigBeans();
-        for(ObjectName on: objectNames) {
+        for (ObjectName on : objectNames) {
             transaction4.destroyModule(on);
         }
         transaction4.commit();
@@ -118,8 +117,8 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
         assertTrue(serviceMapping.isEmpty());
     }
 
-    private void checkApspThreadCount(final int fixedNrOfThreads) throws MBeanException, AttributeNotFoundException,
-            InstanceNotFoundException, ReflectionException {
+    private void checkApspThreadCount(final int fixedNrOfThreads)
+            throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
         ObjectName apspON = ObjectNameUtil.createReadOnlyModuleON(TestingParallelAPSPModuleFactory.NAME, apsp1);
         assertEquals(fixedNrOfThreads, platformMBeanServer.getAttribute(apspON, "MaxNumberOfThreads"));
     }
index 20a127ed23820c49e57ff4cb818b1f6b487c9748..0f099e77b0eb32b29f1d8c79414ab3c17b8cfa2c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -34,10 +34,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
 
     final ModuleIdentifier apspName = new ModuleIdentifier("apsp", "apsp"); // depends
                                                                             // on:
-    final ModuleIdentifier threadPoolName = new ModuleIdentifier("threadpool",
-            "threadpool"); // depends on:
-    final ModuleIdentifier threadFactoryName = new ModuleIdentifier(
-            "threadfactory", "threadfactory");
+    final ModuleIdentifier threadPoolName = new ModuleIdentifier("threadpool", "threadpool"); // depends on:
+    final ModuleIdentifier threadFactoryName = new ModuleIdentifier("threadfactory", "threadfactory");
 
     private DependencyResolverManager tested;
     TransactionStatus transactionStatus;
@@ -54,10 +52,9 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
 
     @Test
     public void testOrdering() {
-        DependencyResolverImpl apspDRI = tested.getOrCreate(apspName);
+        final DependencyResolverImpl apspDRI = tested.getOrCreate(apspName);
         mockGetInstance(tested, apspName);
-        DependencyResolverImpl threadPoolDRI = tested
-                .getOrCreate(threadPoolName);
+        final DependencyResolverImpl threadPoolDRI = tested.getOrCreate(threadPoolName);
         mockGetInstance(tested, threadPoolName);
         tested.getOrCreate(threadFactoryName);
         mockGetInstance(tested, threadFactoryName);
@@ -73,12 +70,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
         doNothing().when(transactionStatus).checkCommitted();
         doNothing().when(transactionStatus).checkNotCommitted();
 
-        List<ModuleIdentifier> sortedModuleIdentifiers = tested
-                .getSortedModuleIdentifiers();
-        assertEquals(
-                Arrays.asList(threadFactoryName, threadPoolName, apspName),
-                sortedModuleIdentifiers);
-
+        List<ModuleIdentifier> sortedModuleIdentifiers = tested.getSortedModuleIdentifiers();
+        assertEquals(Arrays.asList(threadFactoryName, threadPoolName, apspName), sortedModuleIdentifiers);
     }
 
     /**
@@ -88,8 +81,7 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
     private static void declareDependency(final DependencyResolverImpl dependerResolver,
             final ModuleIdentifier dependentName) {
         JmxAttribute dummyAttribute = new JmxAttribute("dummy");
-        dependerResolver.resolveInstance(Object.class,
-                ObjectNameUtil.createReadOnlyModuleON(dependentName),
+        dependerResolver.resolveInstance(Object.class, ObjectNameUtil.createReadOnlyModuleON(dependentName),
                 dummyAttribute);
     }
 
@@ -101,12 +93,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
         TransactionModuleJMXRegistration transactionModuleJMXRegistration = null;
         boolean isDefaultBean = false;
 
-        tested.put(moduleIdentifier,
-            mockedModule(),
-            moduleFactory,
-            maybeOldInternalInfo,
-            transactionModuleJMXRegistration,
-            isDefaultBean, mock(BundleContext.class));
+        tested.put(moduleIdentifier, mockedModule(), moduleFactory, maybeOldInternalInfo,
+                transactionModuleJMXRegistration, isDefaultBean, mock(BundleContext.class));
     }
 
     private static Module mockedModule() {
@@ -115,5 +103,4 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe
         doReturn(new ModuleIdentifier("fact", "instance")).when(mockedModule).getIdentifier();
         return mockedModule;
     }
-
 }
index afd088c62fb1b7b3696910672fd3beb503b5b448..6f65a1e1531644d41478a9f728b1e6e9dd417a57 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -30,35 +30,31 @@ import org.opendaylight.controller.config.manager.testingservices.threadpool.Tes
 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
 import org.opendaylight.controller.config.spi.Module;
 
-public abstract class AbstractDynamicWrapperTest extends
-        AbstractLockedPlatformMBeanServerTest {
-    protected final MBeanServer platformMBeanServer = ManagementFactory
-            .getPlatformMBeanServer();
-    private static final String moduleName = "impl";
-    protected final ObjectName threadPoolDynamicWrapperON = ObjectNameUtil
-            .createReadOnlyModuleON(moduleName, "fixed1");
+public abstract class AbstractDynamicWrapperTest extends AbstractLockedPlatformMBeanServerTest {
+    protected final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
+    private static final String MODULE_NAME = "impl";
+    protected final ObjectName threadPoolDynamicWrapperON =
+            ObjectNameUtil.createReadOnlyModuleON(MODULE_NAME, "fixed1");
     protected static final String THREAD_COUNT = "ThreadCount";
     protected static final String TRIGGER_NEW_INSTANCE_CREATION = "TriggerNewInstanceCreation";
 
     protected final int threadCount = 5;
     protected TestingFixedThreadPoolModule threadPoolConfigBean;
-    private static final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(
-            moduleName, "clientname2");
+    private static final ModuleIdentifier MODULE_IDENTIFIER =
+            new ModuleIdentifier(MODULE_NAME, "clientname2");
 
     protected MBeanServer internalServer;
 
     @Before
     public void registerToJMX() throws Exception {
         internalServer = MBeanServerFactory.createMBeanServer();
-        TestingFixedThreadPoolModuleFactory testingFixedThreadPoolConfigBeanFactory = new TestingFixedThreadPoolModuleFactory();
-        threadPoolConfigBean = testingFixedThreadPoolConfigBeanFactory
-                .createModule("", null, null);
+        TestingFixedThreadPoolModuleFactory testingFixedThreadPoolConfigBeanFactory =
+                new TestingFixedThreadPoolModuleFactory();
+        threadPoolConfigBean = testingFixedThreadPoolConfigBeanFactory.createModule("", null, null);
 
         threadPoolConfigBean.setThreadCount(threadCount);
-        AbstractDynamicWrapper dynamicWrapper = getDynamicWrapper(
-                threadPoolConfigBean, moduleIdentifier);
-        platformMBeanServer.registerMBean(dynamicWrapper,
-                threadPoolDynamicWrapperON);
+        AbstractDynamicWrapper dynamicWrapper = getDynamicWrapper(threadPoolConfigBean, MODULE_IDENTIFIER);
+        platformMBeanServer.registerMBean(dynamicWrapper, threadPoolDynamicWrapperON);
     }
 
     @After
@@ -68,42 +64,34 @@ public abstract class AbstractDynamicWrapperTest extends
         MBeanServerFactory.releaseMBeanServer(internalServer);
     }
 
-    protected abstract AbstractDynamicWrapper getDynamicWrapper(Module module,
-            ModuleIdentifier moduleIdentifier);
+    protected abstract AbstractDynamicWrapper getDynamicWrapper(Module module, ModuleIdentifier moduleIdentifier);
 
     @Test
     public void testReadAttributes() throws Exception {
-
-        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer,
-                threadPoolDynamicWrapperON, DynamicMBean.class);
+        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
 
         assertEquals(threadCount, proxy.getAttribute(THREAD_COUNT));
 
         assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(),
                 proxy.getAttribute(TRIGGER_NEW_INSTANCE_CREATION));
 
-        AttributeList attributes = proxy.getAttributes(new String[] {
-            THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
+        AttributeList attributes = proxy.getAttributes(new String[] { THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
         assertEquals(2, attributes.size());
         Attribute threadCountAttr = (Attribute) attributes.get(0);
         assertEquals(THREAD_COUNT, threadCountAttr.getName());
         assertEquals(threadCount, threadCountAttr.getValue());
         Attribute boolTestAttr = (Attribute) attributes.get(1);
         assertEquals(TRIGGER_NEW_INSTANCE_CREATION, boolTestAttr.getName());
-        assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(),
-                boolTestAttr.getValue());
-
-        MBeanInfo mBeanInfo = proxy.getMBeanInfo();
-        assertEquals(2, mBeanInfo.getAttributes().length);
+        assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), boolTestAttr.getValue());
 
+        MBeanInfo beanInfo = proxy.getMBeanInfo();
+        assertEquals(2, beanInfo.getAttributes().length);
     }
 
     @Test
     public void testGettersWithMXBeanProxy() {
-        TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(
-                platformMBeanServer, threadPoolDynamicWrapperON,
+        TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON,
                 TestingFixedThreadPoolConfigMXBean.class);
         assertEquals(threadCount, proxy.getThreadCount());
     }
-
 }
index 854b40eb241382bd46c863f3ddc651db6e3bacf8..4efbebbf4676263291d3b628e65288812843dbeb 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -36,8 +36,7 @@ public class AnnotationsTest {
     private static void assertRequireInterfaceAnnotationHasCorrectValue(final Class<?> clazz, final String methodName,
             final Set<Class<?>> inspectedInterfaces, final Class<? extends AbstractServiceInterface> expectedValue) {
         Method setter = findMethod(clazz, methodName);
-        RequireInterface found = AttributeHolder
-                .findRequireInterfaceAnnotation(setter, inspectedInterfaces);
+        RequireInterface found = AttributeHolder.findRequireInterfaceAnnotation(setter, inspectedInterfaces);
         if (expectedValue == null) {
             assertNull(found);
         } else {
@@ -50,7 +49,7 @@ public class AnnotationsTest {
         Method setter;
         try {
             setter = clazz.getMethod(methodName, new Class[] { ObjectName.class });
-        } catch (final Exception e) {
+        } catch (final NoSuchMethodException e) {
             throw Throwables.propagate(e);
         }
         return setter;
@@ -59,8 +58,7 @@ public class AnnotationsTest {
     private static void assertDescription(final Class<?> clazz, final String methodName,
             final Set<Class<?>> exportedInterfaces, final String expectedValue) {
         Method setter = findMethod(clazz, methodName);
-        String found = AttributeHolder.findDescription(setter,
-                exportedInterfaces);
+        String found = AttributeHolder.findDescription(setter, exportedInterfaces);
         if (expectedValue == null) {
             assertNull(found);
         } else {
@@ -88,10 +86,10 @@ public class AnnotationsTest {
     static final String SIMPLE = "simple";
     static final String SUBCLASS2 = "subclass2";
 
-    @ServiceInterfaceAnnotation(value = SIMPLE, osgiRegistrationType = Executor.class,
-        namespace = "ns", revision = "rev", localName = SIMPLE)
+    @ServiceInterfaceAnnotation(value = SIMPLE,
+            osgiRegistrationType = Executor.class,
+            namespace = "ns", revision = "rev", localName = SIMPLE)
     interface SimpleSI extends AbstractServiceInterface {
-
     }
 
     @Description("class")
@@ -109,12 +107,10 @@ public class AnnotationsTest {
 
     @Test
     public void testFindAnnotation_directly() throws Exception {
-        assertRequireInterfaceAnnotationHasCorrectValue(SuperClass.class,
-                setSomethingString, emptySetOfInterfaces(), SimpleSI.class);
-        assertDescription(SuperClass.class, setSomethingString,
-                emptySetOfInterfaces(), "descr");
-        assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(),
-                "class");
+        assertRequireInterfaceAnnotationHasCorrectValue(SuperClass.class, setSomethingString, emptySetOfInterfaces(),
+                SimpleSI.class);
+        assertDescription(SuperClass.class, setSomethingString, emptySetOfInterfaces(), "descr");
+        assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class");
     }
 
     public static class SubClassWithout extends SuperClass {
@@ -123,12 +119,10 @@ public class AnnotationsTest {
 
     @Test
     public void testFindAnnotation_subclassWithout() throws Exception {
-        assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithout.class,
-                setSomethingString, emptySetOfInterfaces(), SimpleSI.class);
-        assertDescription(SubClassWithout.class, setSomethingString,
-                emptySetOfInterfaces(), "descr");
-        assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(),
-                "class");
+        assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithout.class, setSomethingString,
+                emptySetOfInterfaces(), SimpleSI.class);
+        assertDescription(SubClassWithout.class, setSomethingString, emptySetOfInterfaces(), "descr");
+        assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class");
     }
 
     public static class SubClassWithEmptyMethod extends SuperClass {
@@ -140,23 +134,19 @@ public class AnnotationsTest {
 
     @Test
     public void testOverridingWithoutAnnotation() throws Exception {
-        assertRequireInterfaceAnnotationHasCorrectValue(
-                SubClassWithEmptyMethod.class, setSomethingString,
+        assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithEmptyMethod.class, setSomethingString,
                 emptySetOfInterfaces(), SimpleSI.class);
-        assertDescription(SubClassWithEmptyMethod.class, setSomethingString,
-                emptySetOfInterfaces(), "descr");
-        assertDescriptionOnClass(SubClassWithEmptyMethod.class,
-                emptySetOfInterfaces(), "class");
+        assertDescription(SubClassWithEmptyMethod.class, setSomethingString, emptySetOfInterfaces(), "descr");
+        assertDescriptionOnClass(SubClassWithEmptyMethod.class, emptySetOfInterfaces(), "class");
     }
 
     interface SubSI extends SimpleSI {
 
     }
 
-    @ServiceInterfaceAnnotation(value = SUBCLASS2, osgiRegistrationType = ExecutorService.class,
-        namespace = "ns", revision = "rev", localName = SUBCLASS2)
+    @ServiceInterfaceAnnotation(value = SUBCLASS2,
+            osgiRegistrationType = ExecutorService.class, namespace = "ns", revision = "rev", localName = SUBCLASS2)
     interface SubSI2 extends SubSI {
-
     }
 
     public static class SubClassWithAnnotation extends SuperClass {
@@ -173,11 +163,11 @@ public class AnnotationsTest {
         assertDescription(SubClassWithAnnotation.class, setSomethingString, emptySetOfInterfaces(), "descr2\ndescr");
         try {
             assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithAnnotation.class, setSomethingString,
-                emptySetOfInterfaces(), SubSI2.class);
+                    emptySetOfInterfaces(), SubSI2.class);
             fail();
         } catch (final IllegalStateException e) {
             assertTrue(e.getMessage(),
-                e.getMessage().startsWith("Error finding @RequireInterface. More than one value specified"));
+                    e.getMessage().startsWith("Error finding @RequireInterface. More than one value specified"));
         }
     }
 
@@ -190,39 +180,31 @@ public class AnnotationsTest {
     }
 
     @Test
-    public void testFindAnnotation_SubClassWithoutMethodWithInterface()
-            throws Exception {
-        assertRequireInterfaceAnnotationHasCorrectValue(
-                SubClassWithoutMethodWithInterface.class, setSomethingString,
+    public void testFindAnnotation_SubClassWithoutMethodWithInterface() throws Exception {
+        assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithoutMethodWithInterface.class, setSomethingString,
                 emptySetOfInterfaces(), SimpleSI.class);
-        assertDescription(SubClassWithoutMethodWithInterface.class,
-                setSomethingString, emptySetOfInterfaces(), "descr");
+        assertDescription(SubClassWithoutMethodWithInterface.class, setSomethingString, emptySetOfInterfaces(),
+                "descr");
     }
 
-    static abstract class SuperClassWithInterface implements HasSomeMethod {
+    abstract static class SuperClassWithInterface implements HasSomeMethod {
         @Override
         @RequireInterface(SubSI2.class)
         @Description("descr")
         public void setSomething(final ObjectName objectName) {
-
         }
     }
 
     @Description("class")
     public static class SubClassOfSuperClassWithInterface extends SuperClassWithInterface {
-
     }
 
     @Test
-    public void testFindAnnotation_SubClassOfSuperClassWithInterface()
-            throws Exception {
-        assertRequireInterfaceAnnotationHasCorrectValue(
-                SubClassOfSuperClassWithInterface.class, setSomethingString,
+    public void testFindAnnotation_SubClassOfSuperClassWithInterface() throws Exception {
+        assertRequireInterfaceAnnotationHasCorrectValue(SubClassOfSuperClassWithInterface.class, setSomethingString,
                 emptySetOfInterfaces(), SubSI2.class);
-        assertDescription(SubClassOfSuperClassWithInterface.class,
-                setSomethingString, emptySetOfInterfaces(), "descr");
-        assertDescriptionOnClass(SubClassOfSuperClassWithInterface.class,
-                emptySetOfInterfaces(), "class");
+        assertDescription(SubClassOfSuperClassWithInterface.class, setSomethingString, emptySetOfInterfaces(), "descr");
+        assertDescriptionOnClass(SubClassOfSuperClassWithInterface.class, emptySetOfInterfaces(), "class");
     }
 
     @Test
@@ -245,8 +227,7 @@ public class AnnotationsTest {
 
     @Test
     public void testHasSomeMethodWithAnnotationsImpl() {
-        HashSet<Class<?>> exportedInterfaces = Sets
-                .<Class<?>> newHashSet(HasSomeMethodWithAnnotations.class);
+        HashSet<Class<?>> exportedInterfaces = Sets.<Class<?>>newHashSet(HasSomeMethodWithAnnotations.class);
         assertRequireInterfaceAnnotationHasCorrectValue(HasSomeMethodWithAnnotationsImpl.class, setSomethingString,
                 exportedInterfaces, SubSI2.class);
 
index 100ed62b82bbeb1bd0c9472d9aaea2384ead9d5a..48accc56ac228e8f5b1f90b84f50b5284ad0e3bd 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,6 +9,7 @@ package org.opendaylight.controller.config.manager.impl.dynamicmbean;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
+
 import java.util.concurrent.atomic.AtomicBoolean;
 import javax.management.Attribute;
 import javax.management.AttributeList;
@@ -29,22 +30,17 @@ import org.opendaylight.controller.config.spi.Module;
 public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
     private final int newThreadCount = 10;
     private final AtomicBoolean atomicBoolean = new AtomicBoolean();
-    private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(
-            atomicBoolean);
+    private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(atomicBoolean);
 
     @Override
-    protected AbstractDynamicWrapper getDynamicWrapper(final Module module,
-            final ModuleIdentifier moduleIdentifier) {
-        return new DynamicWritableWrapper(module, moduleIdentifier,
-                "transaction-1",
-                readOnlyAtomicBoolean, MBeanServerFactory.createMBeanServer(),
-                platformMBeanServer);
+    protected AbstractDynamicWrapper getDynamicWrapper(final Module module, final ModuleIdentifier moduleIdentifier) {
+        return new DynamicWritableWrapper(module, moduleIdentifier, "transaction-1", readOnlyAtomicBoolean,
+                MBeanServerFactory.createMBeanServer(), platformMBeanServer);
     }
 
     @Test
     public void testSetAttribute() throws Exception {
-        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer,
-                threadPoolDynamicWrapperON, DynamicMBean.class);
+        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
 
         proxy.setAttribute(new Attribute(THREAD_COUNT, newThreadCount));
 
@@ -63,40 +59,31 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
 
     @Test
     public void testSettersWithMXBeanProxy() {
-        TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(
-                platformMBeanServer, threadPoolDynamicWrapperON,
+        TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON,
                 TestingFixedThreadPoolConfigMXBean.class);
         proxy.setThreadCount(newThreadCount);
         assertEquals(newThreadCount, threadPoolConfigBean.getThreadCount());
     }
 
     /*
-     * Try to call setter with ObjectName containing transaction name. Verify
-     * that ObjectName without transaction name was actually passed on the
-     * config bean.
+     * Try to call setter with ObjectName containing transaction name. Verify that
+     * ObjectName without transaction name was actually passed on the config bean.
      */
     @Test
-    public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON()
-            throws Exception {
+    public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON() throws Exception {
         TestingParallelAPSPModuleFactory testingParallelAPSPConfigBeanFactory = new TestingParallelAPSPModuleFactory();
-        TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory
-                .createModule("", null, null);
-        ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp",
-                "parallel");
-        ObjectName dynON2 = ObjectNameUtil
-                .createReadOnlyModuleON(moduleIdentifier2);
-        AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean,
-                moduleIdentifier2);
+        TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory.createModule("", null, null);
+        ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp", "parallel");
+        ObjectName dynON2 = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier2);
+        AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean, moduleIdentifier2);
         platformMBeanServer.registerMBean(dyn, dynON2);
         try {
-            TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy(
-                    platformMBeanServer, dynON2,
+            TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy(platformMBeanServer, dynON2,
                     TestingParallelAPSPConfigMXBean.class);
-            ObjectName withTransactionName = ObjectNameUtil
-                    .createTransactionModuleON("transaction1", "moduleName", "instanceName");
+            ObjectName withTransactionName = ObjectNameUtil.createTransactionModuleON("transaction1", "moduleName",
+                    "instanceName");
             proxy.setThreadPool(withTransactionName);
-            ObjectName withoutTransactionName = ObjectNameUtil
-                    .withoutTransactionName(withTransactionName);
+            ObjectName withoutTransactionName = ObjectNameUtil.withoutTransactionName(withTransactionName);
             assertEquals(withoutTransactionName, proxy.getThreadPool());
         } finally {
             platformMBeanServer.unregisterMBean(dynON2);
@@ -104,8 +91,7 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
     }
 
     private void setNumberOfThreads(final int numberOfThreads) throws Exception {
-        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer,
-                threadPoolDynamicWrapperON, DynamicMBean.class);
+        DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
 
         proxy.setAttribute(new Attribute(THREAD_COUNT, numberOfThreads));
 
@@ -123,7 +109,5 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
         } finally {
             atomicBoolean.set(false);
         }
-
     }
-
 }
index 969192c6217948bfe306839e46530e29198bd92b..b6cc61e1e3175c289ea607ee4f405876819ef045 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -7,34 +7,21 @@
  */
 package org.opendaylight.controller.config.manager.impl.factoriesresolver;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import java.io.Closeable;
 import java.util.AbstractMap;
-import java.util.Arrays;
-import java.util.Dictionary;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
 
 public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver {
-    private Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
+    private final Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
 
     public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) {
         this.factories = new HashMap<>(list.length);
         for (ModuleFactory moduleFactory : list) {
             String moduleName = moduleFactory.getImplementationName();
             if (moduleName == null || moduleName.isEmpty()) {
-                throw new IllegalStateException(
-                        "Invalid implementation name for " + moduleFactory);
+                throw new IllegalStateException("Invalid implementation name for " + moduleFactory);
             }
             Map.Entry<ModuleFactory, BundleContext> conflicting = factories.get(moduleName);
             if (conflicting == null) {
@@ -47,19 +34,8 @@ public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver
         }
     }
 
-    private static BundleContext mockBundleContext() {
-        BundleContext bundleContext = Mockito.mock(BundleContext.class);
-        ServiceRegistration<ModuleFactory> serviceRegistration = mock(ServiceRegistration.class);
-        doNothing().when(serviceRegistration).unregister();
-        doReturn(serviceRegistration).when(bundleContext).registerService(
-                Matchers.any(String[].class), any(Closeable.class),
-                any(Dictionary.class));
-        return bundleContext;
-    }
-
     @Override
     public Map<String, Map.Entry<ModuleFactory, BundleContext>> getAllFactories() {
         return factories;
     }
-
 }
index 7d426be66289e5a6b58b01702a9e17746c385255..ca21fef902448df925a4f7f472d1147d39fdb67c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -52,7 +52,8 @@ public class BlankTransactionServiceTrackerTest {
     @Test
     public void testValidationException() throws Exception {
         IllegalArgumentException argumentException = new IllegalArgumentException();
-        ValidationException validationException = ValidationException.createForSingleException(new ModuleIdentifier("m", "i"), argumentException);
+        ValidationException validationException = ValidationException
+                .createForSingleException(new ModuleIdentifier("m", "i"), argumentException);
         doThrow(validationException).when(blankTx).hit();
 
         tracker.addingService(getMockServiceReference());
index cf50098e09de8b0a4f13fcab8595af9c6cfcabd1..4ac414616b751944e5d2819cbb8939947e7bd66b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -79,6 +79,7 @@ public class BundleContextBackedModuleFactoriesResolverTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testDuplicateFactories() throws Exception {
         doReturn(f1).when(bundleContext).getService(s2);
         try {
index d694e981d6ed3af673c2223fd4307c9df6af9801..7d48ad17ed6df2760f762359d40607dac82d47b1 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -19,14 +19,13 @@ import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyZeroInteractions;
+
 import java.util.Dictionary;
 import java.util.Set;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 import org.opendaylight.controller.config.api.DependencyResolver;
 import org.opendaylight.controller.config.api.DependencyResolverFactory;
 import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
@@ -50,12 +49,8 @@ public class ModuleFactoryBundleTrackerTest {
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        doAnswer(new Answer<Object>() {
-            @Override
-            public Object answer(final InvocationOnMock invocation) throws Throwable {
-                return getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]);
-            }
-        }).when(bundle).loadClass(anyString());
+        doAnswer(invocation -> getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]))
+                .when(bundle).loadClass(anyString());
         doReturn("mockBundle").when(bundle).toString();
         doReturn(context).when(bundle).getBundleContext();
         doReturn(reg).when(context).registerService(anyString(), anyObject(), any(Dictionary.class));
@@ -68,6 +63,7 @@ public class ModuleFactoryBundleTrackerTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testRegisterFactoryInstantiateEx() throws Exception {
         try {
             ModuleFactoryBundleTracker.registerFactory(WrongConstructorTestingFactory.class.getName(), bundle);
@@ -82,6 +78,7 @@ public class ModuleFactoryBundleTrackerTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testRegisterFactoryInstantiateExAccess() throws Exception {
         try {
             ModuleFactoryBundleTracker.registerFactory(NoAccessConstructorTestingFactory.class.getName(), bundle);
@@ -96,6 +93,7 @@ public class ModuleFactoryBundleTrackerTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testRegisterFactoryNotExtending() throws Exception {
         try {
             ModuleFactoryBundleTracker.registerFactory(NotExtendingTestingFactory.class.getName(), bundle);
@@ -108,6 +106,7 @@ public class ModuleFactoryBundleTrackerTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testRegisterFactoryNotExisting() throws Exception {
         try {
             ModuleFactoryBundleTracker.registerFactory("Unknown class", bundle);
@@ -133,6 +132,7 @@ public class ModuleFactoryBundleTrackerTest {
     }
 
     @Test
+    @SuppressWarnings("IllegalCatch")
     public void testAddingBundleError() throws Exception {
         final ModuleFactoryBundleTracker tracker = new ModuleFactoryBundleTracker(blankTxTracker);
         doReturn(getClass().getResource("/module-factories/module-factory-fail")).when(bundle).getEntry(anyString());
@@ -151,7 +151,8 @@ public class ModuleFactoryBundleTrackerTest {
         }
     }
 
-    static class NotExtendingTestingFactory {}
+    static class NotExtendingTestingFactory {
+    }
 
     static class NoAccessConstructorTestingFactory extends TestingFactory {
         private NoAccessConstructorTestingFactory() {
@@ -172,17 +173,20 @@ public class ModuleFactoryBundleTrackerTest {
         }
 
         @Override
-        public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
+        public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+                final BundleContext bundleContext) {
             throw new UnsupportedOperationException();
         }
 
         @Override
-        public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
+        public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+                final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
             throw new UnsupportedOperationException();
         }
 
         @Override
-        public boolean isModuleImplementingServiceInterface(final Class<? extends AbstractServiceInterface> serviceInterface) {
+        public boolean isModuleImplementingServiceInterface(
+                final Class<? extends AbstractServiceInterface> serviceInterface) {
             throw new UnsupportedOperationException();
         }
 
@@ -192,7 +196,8 @@ public class ModuleFactoryBundleTrackerTest {
         }
 
         @Override
-        public Set<? extends Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+        public Set<? extends Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+                final BundleContext bundleContext) {
             throw new UnsupportedOperationException();
         }
     }
index d0df7a7104847e2aae4c13b5e4468e06edfc59d9..4de2302beb340afdd47505ee6552ebac3d6e1ccc 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -13,6 +13,7 @@ import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
+
 import java.util.Dictionary;
 import org.junit.Before;
 import org.junit.Test;
@@ -37,7 +38,8 @@ public class RefreshingSCPModuleInfoRegistryTest {
     @Mock
     SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
 
-    @Before public void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
     }
 
@@ -48,7 +50,8 @@ public class RefreshingSCPModuleInfoRegistryTest {
         doReturn("string").when(prov).toString();
         final BundleContext ctxt = mock(BundleContext.class);
         final ServiceRegistration<?> servReg = mock(ServiceRegistration.class);
-        doReturn(servReg).when(ctxt).registerService(any(Class.class), any(SchemaContextProvider.class), any(Dictionary.class));
+        doReturn(servReg).when(ctxt).registerService(any(Class.class), any(SchemaContextProvider.class),
+                any(Dictionary.class));
         doReturn(servReg).when(ctxt).registerService(Mockito.anyString(), any(Object.class), any(Dictionary.class));
         doNothing().when(servReg).setProperties(any(Dictionary.class));
 
@@ -59,7 +62,8 @@ public class RefreshingSCPModuleInfoRegistryTest {
         doReturn("B-runtime-context").when(bindingRuntimeContext).toString();
         doReturn(bindingRuntimeContext).when(codecRegistryProvider).getBindingContext();
 
-        final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, classLoadingStrat, this.sourceProvider, codecRegistryProvider, ctxt);
+        final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, classLoadingStrat,
+                this.sourceProvider, codecRegistryProvider, ctxt);
 
         doNothing().when(servReg).unregister();
 
index 5b19f615bc5b6659c3e87099ff67b2d9bacf4688..e55e4f76b1814ce73f911514dfee888d8634a633 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -29,26 +29,21 @@ import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
 import org.opendaylight.controller.config.manager.impl.jmx.HierarchicalRuntimeBeanRegistrationImpl;
 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
 
-public class RuntimeBeanRegistratorImplTest extends
-        AbstractLockedPlatformMBeanServerTest {
-    static final String module1 = "module1";
-    static final String INSTANCE_NAME = "instanceName";
+public class RuntimeBeanRegistratorImplTest extends AbstractLockedPlatformMBeanServerTest {
+    private static final String MODULE1 = "module1";
+    private static final String INSTANCE_NAME = "instanceName";
     String additionalKey = "key";
     String additionalValue = "value";
-    Map<String, String> additionalProperties = ImmutableMap.of(additionalKey,
-            additionalValue);
+    Map<String, String> additionalProperties = ImmutableMap.of(additionalKey, additionalValue);
 
     private BaseJMXRegistrator baseJMXRegistrator;
     private RootRuntimeBeanRegistratorImpl tested;
-    private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(
-            module1, INSTANCE_NAME);
+    private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(MODULE1, INSTANCE_NAME);
 
     @Before
     public void setUp() {
-        baseJMXRegistrator = new BaseJMXRegistrator(
-                ManagementFactory.getPlatformMBeanServer());
-        tested = baseJMXRegistrator
-                .createRuntimeBeanRegistrator(moduleIdentifier);
+        baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
+        tested = baseJMXRegistrator.createRuntimeBeanRegistrator(moduleIdentifier);
     }
 
     @After
@@ -66,7 +61,7 @@ public class RuntimeBeanRegistratorImplTest extends
             platformMBeanServer.getMBeanInfo(on);
             fail();
         } catch (final InstanceNotFoundException e) {
-
+            // FIXME: should it be empty?
         }
     }
 
@@ -75,13 +70,11 @@ public class RuntimeBeanRegistratorImplTest extends
         createRoot();
     }
 
-    private HierarchicalRuntimeBeanRegistrationImpl createRoot()
-            throws Exception {
-        HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested
-                .registerRoot(new TestingRuntimeBean());
+    private HierarchicalRuntimeBeanRegistrationImpl createRoot() throws Exception {
+        HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested.registerRoot(new TestingRuntimeBean());
 
-        ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(module1,
-                INSTANCE_NAME, Maps.<String, String> newHashMap());
+        ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME,
+                Maps.<String, String>newHashMap());
 
         assertEquals(expectedON1, rootRegistration.getObjectName());
         checkExists(rootRegistration.getObjectName());
@@ -95,14 +88,12 @@ public class RuntimeBeanRegistratorImplTest extends
     }
 
     private HierarchicalRuntimeBeanRegistration createAdditional(
-            final HierarchicalRuntimeBeanRegistrationImpl rootRegistration)
-            throws Exception {
+            final HierarchicalRuntimeBeanRegistrationImpl rootRegistration) throws Exception {
 
-        HierarchicalRuntimeBeanRegistrationImpl registration = rootRegistration
-                .register(additionalKey, additionalValue, new TestingRuntimeBean());
+        HierarchicalRuntimeBeanRegistrationImpl registration = rootRegistration.register(additionalKey, additionalValue,
+                new TestingRuntimeBean());
 
-        ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(module1,
-                INSTANCE_NAME, additionalProperties);
+        ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME, additionalProperties);
 
         assertEquals(expectedON1, registration.getObjectName());
         checkExists(registration.getObjectName());
@@ -138,12 +129,9 @@ public class RuntimeBeanRegistratorImplTest extends
             createRoot();
             fail();
         } catch (final IllegalStateException e) {
-            assertThat(e.getMessage(), containsString(rootRegistration
-                    .getObjectName().toString()));
-            assertThat(e.getMessage(),
-                    containsString("Could not register runtime bean"));
-            assertThat(e.getMessage(),
-                    containsString(moduleIdentifier.toString()));
+            assertThat(e.getMessage(), containsString(rootRegistration.getObjectName().toString()));
+            assertThat(e.getMessage(), containsString("Could not register runtime bean"));
+            assertThat(e.getMessage(), containsString(moduleIdentifier.toString()));
         }
     }
 
@@ -153,5 +141,4 @@ public class RuntimeBeanRegistratorImplTest extends
         platformMBeanServer.unregisterMBean(rootRegistration.getObjectName());
         rootRegistration.close();
     }
-
 }
index 5656163cbef7a4ecfe2791cd1d52132db99ab9b0..ba105bc09e4fb7b7757614c7e7d526d06db0afd8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.config.manager.impl.util;
 
 import static org.junit.Assert.assertEquals;
+
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
 import java.util.Collections;
@@ -45,10 +46,15 @@ public class InterfacesHelperTest {
 
     }
 
-    @ServiceInterfaceAnnotation(value = "a", osgiRegistrationType = SuperA.class, namespace = "n", revision = "r", localName = "l")
-    public interface Service extends AbstractServiceInterface{}
-    @ServiceInterfaceAnnotation(value = "b", osgiRegistrationType = SuperC.class, namespace = "n", revision = "r", localName = "l")
-    public interface SubService extends Service{}
+    @ServiceInterfaceAnnotation(value = "a", osgiRegistrationType =
+            SuperA.class, namespace = "n", revision = "r", localName = "l")
+    public interface Service extends AbstractServiceInterface {
+    }
+
+    @ServiceInterfaceAnnotation(value = "b", osgiRegistrationType =
+            SuperC.class, namespace = "n", revision = "r", localName = "l")
+    public interface SubService extends Service {
+    }
 
     public abstract class SubClass extends SuperClass implements SubA, Module {
 
@@ -60,16 +66,16 @@ public class InterfacesHelperTest {
 
     @Test
     public void testGetAllInterfaces() {
-        Set<Class<?>> expected = Sets.<Class<?>> newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class,
-                SubA.class, Identifiable.class, Module.class);
-        assertEquals(expected,
-                InterfacesHelper.getAllInterfaces(SubClass.class));
+        Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class, SubA.class,
+                Identifiable.class, Module.class);
+        assertEquals(expected, InterfacesHelper.getAllInterfaces(SubClass.class));
     }
 
     @Test
     public void testGetServiceInterfaces() throws Exception {
         assertEquals(Collections.<Class<?>>emptySet(), InterfacesHelper.getServiceInterfaces(SubClass.class));
-        assertEquals(Sets.<Class<?>>newHashSet(Service.class, SubService.class), InterfacesHelper.getServiceInterfaces(SubClassWithService.class));
+        assertEquals(Sets.<Class<?>>newHashSet(Service.class, SubService.class),
+                InterfacesHelper.getServiceInterfaces(SubClassWithService.class));
     }
 
     @Test
@@ -81,21 +87,20 @@ public class InterfacesHelperTest {
 
     @Test
     public void testGetMXInterfaces() {
-        Set<Class<?>> expected = Sets.<Class<?>> newHashSet(SuperBMXBean.class, SubA.class);
+        Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperBMXBean.class, SubA.class);
         assertEquals(expected, InterfacesHelper.getMXInterfaces(SubClass.class));
     }
 
     @Test
-    public void testGetAllAbstractServiceInterfaceClasses(){
+    public void testGetAllAbstractServiceInterfaceClasses() {
         Class<? extends AbstractServiceInterface> clazz = TestingScheduledThreadPoolServiceInterface.class;
         Set<Class<? extends AbstractServiceInterface>> input = new HashSet<>();
         input.add(clazz);
-        Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper.getAllAbstractServiceInterfaceClasses(input);
+        Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper
+                .getAllAbstractServiceInterfaceClasses(input);
 
         Set<Class<?>> expected = ImmutableSet.of((Class<?>) TestingScheduledThreadPoolServiceInterface.class,
-                TestingThreadPoolServiceInterface.class
-        );
+                TestingThreadPoolServiceInterface.class);
         assertEquals(expected, result);
     }
-
 }
index 77d48f6ac5347bbf8c501a558c80be3d69807afe..6763facae57247ce7bb149d544c175035537804e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -31,7 +31,8 @@ public class OsgiRegistrationUtilTest {
         ServiceRegistration<?> registration2 = mockServiceRegistration();
         doReturn(registration2).when(bundleContext).registerService(Object.class, "string", null);
 
-        AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class, Object.class);
+        AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class,
+                Object.class);
         aggregatedRegister.close();
 
         InOrder inOrder = Mockito.inOrder(registration, registration2);
@@ -64,6 +65,5 @@ public class OsgiRegistrationUtilTest {
 
     @Test
     public void testAggregate() throws Exception {
-
     }
-}
\ No newline at end of file
+}
index 68f6102987fcb3c8a433df82bf06f70bd5cde190..e215d8853ade8adde5d7ed6e5a6c76c0106643b0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -10,8 +10,9 @@ package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
 import javax.management.ObjectName;
 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
 
-@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME, osgiRegistrationType = TestingAPSP.class,
-    namespace = "namespace", revision = "rev", localName = TestingParallelAPSPConfigMXBean.NAME)
+@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME,
+    osgiRegistrationType = TestingAPSP.class, namespace = "namespace",
+    revision = "rev", localName = TestingParallelAPSPConfigMXBean.NAME)
 public interface TestingParallelAPSPConfigMXBean {
 
     String NAME = "apsp";
@@ -22,9 +23,8 @@ public interface TestingParallelAPSPConfigMXBean {
 
     String getSomeParam();
 
-    void setSomeParam(String s);
+    void setSomeParam(String string);
 
     // for reporting. this should be moved to runtime jmx bean
     Integer getMaxNumberOfThreads();
-
 }
index 2b012a750c24af12e0a1030ccdb52b332dc74c4d..377a1761361123e37e2fdbee29e3743834a4155d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -18,7 +18,7 @@ import org.opendaylight.controller.config.manager.testingservices.threadpool.Tes
 @NotThreadSafe
 public class TestingParallelAPSPImpl implements TestingAPSP, Closeable {
     public static final int MINIMAL_NUMBER_OF_THREADS = 10;
-    private TestingThreadPoolIfc threadPool;
+    private final TestingThreadPoolIfc threadPool;
     private String someParam;
 
     public TestingParallelAPSPImpl(final TestingThreadPoolIfc threadPool,
@@ -46,14 +46,13 @@ public class TestingParallelAPSPImpl implements TestingAPSP, Closeable {
         return threadPool;
     }
 
-    void setSomeParam(final String s) {
+    void setSomeParam(final String string) {
         checkArgument(Strings.isNullOrEmpty(someParam) == false,
                 "Parameter 'someParam' is blank");
-        this.someParam = s;
+        this.someParam = string;
     }
 
     public String getSomeParam() {
         return someParam;
     }
-
 }
index 774ddac4e82be0a93ba8f95c7cc1a4a484cb0a32..656cf04c28aaa0b8c97e01ea5844aa64244025dd 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -14,7 +14,11 @@ import com.google.common.base.Strings;
 import java.io.Closeable;
 import javax.annotation.Nullable;
 import javax.annotation.concurrent.NotThreadSafe;
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
 import javax.management.ObjectName;
+import javax.management.ReflectionException;
 import org.opendaylight.controller.config.api.DependencyResolver;
 import org.opendaylight.controller.config.api.JmxAttribute;
 import org.opendaylight.controller.config.api.ModuleIdentifier;
@@ -30,10 +34,8 @@ import org.slf4j.LoggerFactory;
  * Represents service that has dependency to thread pool.
  */
 @NotThreadSafe
-public class TestingParallelAPSPModule implements Module,
-        TestingParallelAPSPConfigMXBean {
-    private static final Logger LOG = LoggerFactory
-            .getLogger(TestingParallelAPSPModule.class);
+public class TestingParallelAPSPModule implements Module, TestingParallelAPSPConfigMXBean {
+    private static final Logger LOG = LoggerFactory.getLogger(TestingParallelAPSPModule.class);
 
     private final DependencyResolver dependencyResolver;
     private final AutoCloseable oldCloseable;
@@ -43,10 +45,8 @@ public class TestingParallelAPSPModule implements Module,
     private TestingParallelAPSPImpl instance;
     private String someParam;
 
-    public TestingParallelAPSPModule(final ModuleIdentifier identifier,
-            final DependencyResolver dependencyResolver,
-            @Nullable final AutoCloseable oldCloseable,
-            @Nullable final TestingParallelAPSPImpl oldInstance) {
+    public TestingParallelAPSPModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver,
+            @Nullable final AutoCloseable oldCloseable, @Nullable final TestingParallelAPSPImpl oldInstance) {
         this.identifier = identifier;
         this.dependencyResolver = dependencyResolver;
         this.oldCloseable = oldCloseable;
@@ -76,50 +76,50 @@ public class TestingParallelAPSPModule implements Module,
 
     @Override
     public Integer getMaxNumberOfThreads() {
-        if (instance == null)
+        if (instance == null) {
             return null;
+        }
         return instance.getMaxNumberOfThreads();
     }
 
     // this would be generated:
-    private final JmxAttribute threadPoolONJMXAttribute = new JmxAttribute("threadPoolON");
+    private final JmxAttribute threadPoolOnJMXAttribute = new JmxAttribute("threadPoolON");
 
     @Override
     public void validate() {
         checkNotNull(threadPoolON, "Parameter 'threadPool' must be set");
-        dependencyResolver.validateDependency(
-                TestingThreadPoolServiceInterface.class, threadPoolON,
-                threadPoolONJMXAttribute);
+        dependencyResolver.validateDependency(TestingThreadPoolServiceInterface.class, threadPoolON,
+                threadPoolOnJMXAttribute);
 
-        checkState(Strings.isNullOrEmpty(someParam) == false,
-                "Parameter 'SomeParam' is blank");
+        checkState(Strings.isNullOrEmpty(someParam) == false, "Parameter 'SomeParam' is blank");
         // check that calling resolveInstance fails
         try {
-            dependencyResolver.resolveInstance(TestingThreadPoolIfc.class,
-                    threadPoolON, threadPoolONJMXAttribute);
+            dependencyResolver.resolveInstance(TestingThreadPoolIfc.class, threadPoolON, threadPoolOnJMXAttribute);
             throw new RuntimeException("fail");
         } catch (final IllegalStateException e) {
-            checkState("Commit was not triggered".equals(e.getMessage()),
-                    e.getMessage());
+            checkState("Commit was not triggered".equals(e.getMessage()), e.getMessage());
         }
 
         // test retrieving dependent module's attribute
         int threadCount;
         try {
-            threadCount = (Integer)dependencyResolver.getAttribute(threadPoolON, "ThreadCount");
-        } catch (final Exception e) {
+            threadCount = (Integer) dependencyResolver.getAttribute(threadPoolON, "ThreadCount");
+        } catch (final ReflectionException | InstanceNotFoundException | AttributeNotFoundException
+                | MBeanException e) {
             throw new IllegalStateException(e);
         }
         checkState(threadCount > 0);
-        TestingThreadPoolConfigMXBean proxy = dependencyResolver.newMXBeanProxy(threadPoolON, TestingThreadPoolConfigMXBean.class);
+        TestingThreadPoolConfigMXBean proxy = dependencyResolver.newMXBeanProxy(threadPoolON,
+                TestingThreadPoolConfigMXBean.class);
         checkState(threadCount == proxy.getThreadCount());
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public Closeable getInstance() {
         if (instance == null) {
-            TestingThreadPoolIfc threadPoolInstance = dependencyResolver
-                    .resolveInstance(TestingThreadPoolIfc.class, threadPoolON, threadPoolONJMXAttribute);
+            TestingThreadPoolIfc threadPoolInstance = dependencyResolver.resolveInstance(TestingThreadPoolIfc.class,
+                    threadPoolON, threadPoolOnJMXAttribute);
 
             if (oldInstance != null) {
                 // changing thread pool is not supported
@@ -139,8 +139,7 @@ public class TestingParallelAPSPModule implements Module,
                         throw new RuntimeException(e);
                     }
                 }
-                instance = new TestingParallelAPSPImpl(threadPoolInstance,
-                        someParam);
+                instance = new TestingParallelAPSPImpl(threadPoolInstance, someParam);
             }
         }
         return instance;
@@ -155,6 +154,4 @@ public class TestingParallelAPSPModule implements Module,
     public ModuleIdentifier getIdentifier() {
         return identifier;
     }
-
-
 }
index 3fc07fe571a9fe1323eab1a1a1e943a7872d9ec9..4ce5dc91dd687e77d1df5d1956f8467a69746214 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -34,23 +34,21 @@ public class TestingParallelAPSPModuleFactory implements ModuleFactory {
     @Override
     public TestingParallelAPSPModule createModule(final String instanceName,
             final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        return new TestingParallelAPSPModule(new ModuleIdentifier(NAME,
-                instanceName), dependencyResolver, null, null);
+        return new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName), dependencyResolver, null, null);
     }
 
     @Override
     public TestingParallelAPSPModule createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext context)
-            throws Exception {
+            final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old,
+            final BundleContext context) throws Exception {
         TestingParallelAPSPImpl oldInstance;
         try {
             oldInstance = (TestingParallelAPSPImpl) old.getInstance();
         } catch (final ClassCastException e) {
             oldInstance = null;
         }
-        TestingParallelAPSPModule result = new TestingParallelAPSPModule(
-                new ModuleIdentifier(NAME, instanceName), dependencyResolver,
-                old.getInstance(), oldInstance);
+        TestingParallelAPSPModule result = new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName),
+                dependencyResolver, old.getInstance(), oldInstance);
         // copy attributes
         String someParam = (String) old.getAttribute("SomeParam");
         result.setSomeParam(someParam);
@@ -66,7 +64,8 @@ public class TestingParallelAPSPModuleFactory implements ModuleFactory {
     }
 
     @Override
-    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext context) {
+    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+            final BundleContext context) {
         return new HashSet<>();
     }
 
index 9c550966e62228e0bcc5414758fc7db9fa753d99..e6f54908643d17fe8f5206765327d6bf5dca79af 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -12,6 +12,7 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+
 import java.util.Map;
 import javax.management.ObjectName;
 import org.junit.After;
@@ -36,8 +37,7 @@ public class DependentWiringTest extends AbstractParallelAPSPTest {
     @Before
     public void setUp() {
         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
-                new TestingFixedThreadPoolModuleFactory(),
-                new TestingParallelAPSPModuleFactory()));
+                new TestingFixedThreadPoolModuleFactory(), new TestingParallelAPSPModuleFactory()));
     }
 
     @After
@@ -54,29 +54,24 @@ public class DependentWiringTest extends AbstractParallelAPSPTest {
     public void testDependencies() throws Exception {
         ObjectName apspON;
         {
-            ConfigTransactionJMXClient transaction = configRegistryClient
-                    .createTransaction();
+            ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
             // create fixed1
             ObjectName threadPoolTransactionON = createFixed1(transaction,
                     TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS);
             // create apsp-parallel
-            ObjectName apspNameTransactionON = createParallelAPSP(transaction,
-                    threadPoolTransactionON);
-            TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction
-                    .newMXBeanProxy(apspNameTransactionON, TestingParallelAPSPConfigMXBean.class);
+            ObjectName apspNameTransactionON = createParallelAPSP(transaction, threadPoolTransactionON);
+            TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction.newMXBeanProxy(apspNameTransactionON,
+                    TestingParallelAPSPConfigMXBean.class);
             parallelAPSPConfigProxy.setSomeParam("");// trigger validation
-                                                     // failure
+                                                        // failure
             try {
                 transaction.validateConfig();
                 fail();
             } catch (final ValidationException e) {
-                for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
-                        .getFailedValidations().entrySet()) {
-                    for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
-                            .getValue().entrySet()) {
-                        assertThat(
-                                entry.getValue().getMessage(),
-                                containsString("Parameter 'SomeParam' is blank"));
+                for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+                        .entrySet()) {
+                    for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+                        assertThat(entry.getValue().getMessage(), containsString("Parameter 'SomeParam' is blank"));
                     }
                 }
             }
@@ -86,13 +81,11 @@ public class DependentWiringTest extends AbstractParallelAPSPTest {
                 transaction.commit();
                 fail();
             } catch (final ValidationException e) {
-                for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
-                        .getFailedValidations().entrySet()) {
-                    for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
-                            .getValue().entrySet()) {
+                for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+                        .entrySet()) {
+                    for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
                         String err = entry.getValue().getMessage();
-                        assertTrue("Unexpected error message: " + err,
-                                err.contains("Parameter 'SomeParam' is blank"));
+                        assertTrue("Unexpected error message: " + err, err.contains("Parameter 'SomeParam' is blank"));
                     }
                 }
             }
@@ -100,35 +93,30 @@ public class DependentWiringTest extends AbstractParallelAPSPTest {
             parallelAPSPConfigProxy.setSomeParam("abc");// fix validation
                                                         // failure
             transaction.commit();
-            apspON = ObjectNameUtil
-                    .withoutTransactionName(apspNameTransactionON);
+            apspON = ObjectNameUtil.withoutTransactionName(apspNameTransactionON);
         }
 
         // test reported apsp number of threads
-        TestingParallelAPSPConfigMXBean parallelAPSPRuntimeProxy = configRegistryClient
-                .newMXBeanProxy(apspON, TestingParallelAPSPConfigMXBean.class);
-        assertEquals(
-                (Integer) TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS,
+        TestingParallelAPSPConfigMXBean parallelAPSPRuntimeProxy = configRegistryClient.newMXBeanProxy(apspON,
+                TestingParallelAPSPConfigMXBean.class);
+        assertEquals((Integer) TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS,
                 parallelAPSPRuntimeProxy.getMaxNumberOfThreads());
 
         // next transaction - recreate new thread pool
         int newNumberOfThreads = TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS * 2;
         {
             // start new transaction
-            ConfigTransactionJMXClient transaction = configRegistryClient
-                    .createTransaction();
-            ObjectName threadPoolNames_newTx = transaction.lookupConfigBean(
-                    getThreadPoolImplementationName(), fixed1);
+            ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+            ObjectName threadPoolNamesNewTx =
+                    transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
             TestingFixedThreadPoolConfigMXBean fixedConfigTransactionProxy = transaction
-                    .newMXBeanProxy(threadPoolNames_newTx, TestingFixedThreadPoolConfigMXBean.class);
+                    .newMXBeanProxy(threadPoolNamesNewTx, TestingFixedThreadPoolConfigMXBean.class);
             fixedConfigTransactionProxy.setThreadCount(newNumberOfThreads);
 
             transaction.commit();
         }
         // new reference should be copied to apsp-parallel
-        assertEquals((Integer) newNumberOfThreads,
-                parallelAPSPRuntimeProxy.getMaxNumberOfThreads());
-
+        assertEquals((Integer) newNumberOfThreads, parallelAPSPRuntimeProxy.getMaxNumberOfThreads());
     }
 
     @Test
@@ -137,10 +125,9 @@ public class DependentWiringTest extends AbstractParallelAPSPTest {
         ObjectName threadPoolON = createFixed1(transaction, 10);
         transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
         String refName = "ref";
-        ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName,
-                threadPoolON);
+        ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME,
+                refName, threadPoolON);
         createParallelAPSP(transaction, serviceReferenceON);
         transaction.commit();
-
     }
 }
index 9c0f56b1206c65b854b658b844b0a6a1224feb43..459e45838402e601048f688be35a961f011e21bc 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -18,24 +18,21 @@ import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator
 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans.TestingScheduledRuntimeBean;
 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
 
-public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc,
-        TestingScheduledThreadPoolIfc, Closeable {
+public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, TestingScheduledThreadPoolIfc, Closeable {
     private static volatile int numberOfCloseMethodCalls = 0;
     private final ScheduledThreadPoolExecutor executor;
     private final RootRuntimeBeanRegistrator runtimeBeanRegistrator;
 
-    public static final List<ScheduledThreadPoolExecutor> allExecutors = Lists
-            .newLinkedList();
+    public static final List<ScheduledThreadPoolExecutor> ALLEXECUTORS = Lists.newLinkedList();
 
-    public TestingScheduledThreadPoolImpl(
-            final RootRuntimeBeanRegistrator runtimeBeanRegistrator, final int corePoolSize) {
+    public TestingScheduledThreadPoolImpl(final RootRuntimeBeanRegistrator runtimeBeanRegistrator,
+            final int corePoolSize) {
         this.runtimeBeanRegistrator = runtimeBeanRegistrator;
         executor = new ScheduledThreadPoolExecutor(corePoolSize);
-        allExecutors.add(executor);
+        ALLEXECUTORS.add(executor);
         HierarchicalRuntimeBeanRegistration hierarchicalRuntimeBeanRegistration = runtimeBeanRegistrator
                 .registerRoot(new TestingScheduledRuntimeBean());
-        hierarchicalRuntimeBeanRegistration.register("a", "b",
-                new TestingScheduledRuntimeBean());
+        hierarchicalRuntimeBeanRegistration.register("a", "b", new TestingScheduledRuntimeBean());
     }
 
     @Override
@@ -61,15 +58,14 @@ public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc,
     }
 
     public static void cleanUp() {
-        for (ScheduledThreadPoolExecutor executor : allExecutors) {
+        for (ScheduledThreadPoolExecutor executor : ALLEXECUTORS) {
             executor.shutdown();
         }
-        allExecutors.clear();
+        ALLEXECUTORS.clear();
         numberOfCloseMethodCalls = 0;
     }
 
     public static int getNumberOfCloseMethodCalls() {
         return numberOfCloseMethodCalls;
     }
-
 }
index cf0d9d17df07566306ff26f834fa303fe8fcdf31..a16c7c5092ba6506834e121726e1be40512aa882 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -23,10 +23,8 @@ import org.opendaylight.controller.config.spi.Module;
  * This class has two exported interfaces and two runtime beans. Recreation is
  * triggered by setting Recreate attribute to true.
  */
-public class TestingScheduledThreadPoolModule implements Module,
-        TestingScheduledThreadPoolConfigBeanMXBean,
-        RuntimeBeanRegistratorAwareModule,
-        TestingScheduledThreadPoolServiceInterface {
+public class TestingScheduledThreadPoolModule implements Module, TestingScheduledThreadPoolConfigBeanMXBean,
+        RuntimeBeanRegistratorAwareModule, TestingScheduledThreadPoolServiceInterface {
 
     private final ModuleIdentifier identifier;
     @Nullable
@@ -40,16 +38,14 @@ public class TestingScheduledThreadPoolModule implements Module,
     private boolean recreate;
 
     public TestingScheduledThreadPoolModule(final ModuleIdentifier identifier,
-            @Nullable final AutoCloseable oldCloseable,
-            @Nullable final TestingScheduledThreadPoolImpl oldInstance) {
+            @Nullable final AutoCloseable oldCloseable, @Nullable final TestingScheduledThreadPoolImpl oldInstance) {
         this.identifier = identifier;
         this.oldCloseable = oldCloseable;
         this.oldInstance = oldInstance;
     }
 
     @Override
-    public void setRuntimeBeanRegistrator(
-            final RootRuntimeBeanRegistrator runtimeBeanRegistrator) {
+    public void setRuntimeBeanRegistrator(final RootRuntimeBeanRegistrator runtimeBeanRegistrator) {
         this.runtimeBeanRegistrator = runtimeBeanRegistrator;
     }
 
@@ -57,14 +53,13 @@ public class TestingScheduledThreadPoolModule implements Module,
     public void validate() {
         assertNull(runtimeBeanRegistrator);
         // check thread count
-        checkState(threadCount > 0,
-                "Parameter 'ThreadCount' must be greater than 0");
+        checkState(threadCount > 0, "Parameter 'ThreadCount' must be greater than 0");
     }
 
     @Override
     public boolean canReuse(final Module oldModule) {
-        return getClass().isInstance(oldModule) && getThreadCount() ==
-                ((TestingScheduledThreadPoolModule) oldModule).getThreadCount();
+        return getClass().isInstance(oldModule)
+                && getThreadCount() == ((TestingScheduledThreadPoolModule) oldModule).getThreadCount();
     }
 
     @Override
@@ -78,6 +73,7 @@ public class TestingScheduledThreadPoolModule implements Module,
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public Closeable getInstance() {
         assertNotNull(runtimeBeanRegistrator);
         if (instance == null) {
@@ -94,8 +90,7 @@ public class TestingScheduledThreadPoolModule implements Module,
                     }
                 }
                 // close old threadpool and esp. unregister runtime beans
-                instance = new TestingScheduledThreadPoolImpl(
-                        runtimeBeanRegistrator, threadCount);
+                instance = new TestingScheduledThreadPoolImpl(runtimeBeanRegistrator, threadCount);
             }
         }
         return instance;
@@ -116,6 +111,4 @@ public class TestingScheduledThreadPoolModule implements Module,
     public ModuleIdentifier getIdentifier() {
         return identifier;
     }
-
-
 }
index 7428776b76852c60d375880bb0978b97d3560394..1011951055e3605f36aedb16f4d542f0caae8074 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,7 +26,7 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory {
 
     private static Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
             (Class<? extends AbstractServiceInterface>) TestingScheduledThreadPoolServiceInterface.class,
-                    TestingThreadPoolServiceInterface.class);
+            TestingThreadPoolServiceInterface.class);
 
     @Override
     public boolean isModuleImplementingServiceInterface(
@@ -40,33 +40,32 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory {
     }
 
     @Override
-    public Module createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME,
-                instanceName), null, null);
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final BundleContext bundleContext) {
+        return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null);
     }
 
     @Override
-    public Module createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
-            throws Exception {
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
         TestingScheduledThreadPoolImpl oldInstance;
         try {
             oldInstance = (TestingScheduledThreadPoolImpl) old.getInstance();
-        } catch (final ClassCastException e) {// happens after OSGi update
+        } catch (final ClassCastException e) {
+            // happens after OSGi update
             oldInstance = null;
         }
 
         TestingScheduledThreadPoolModule configBean = new TestingScheduledThreadPoolModule(
-                new ModuleIdentifier(NAME, instanceName), old.getInstance(),
-                oldInstance);
+                new ModuleIdentifier(NAME, instanceName), old.getInstance(), oldInstance);
         // copy attributes
         configBean.setRecreate((Boolean) old.getAttribute("Recreate"));
         return configBean;
     }
 
     @Override
-    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+            final BundleContext bundleContext) {
         return new HashSet<>();
     }
 
@@ -74,6 +73,4 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory {
     public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
         return ifc;
     }
-
-
 }
index 998627ede2a99ae9a7a5d141fafec7a3c74bdc24..aac933cf29e3f62bb4ebdf13a9ed5fdca60cc672 100644 (file)
@@ -1,12 +1,14 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 /**
- * Tests config bean that exports two independent interfaces - {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc} and
+ * Tests config bean that exports two independent interfaces -
+ * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc}
+ * and
  * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
  */
 package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
index f686d27ef4fc5b2475bf5228d8b9a7b59f3bee4b..2a9aa16088a3c872a209a085955bc1bef900af6f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -19,7 +19,7 @@ import org.opendaylight.controller.config.manager.testingservices.scheduledthrea
 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
 
 public abstract class AbstractScheduledTest extends AbstractConfigTest {
-    protected static final String scheduled1 = "scheduled1";
+    protected static final String SCHEDULED1 = "scheduled1";
 
     @Before
     public final void setUp() {
index 7b975ceb20bdc5a70f1696be468516bc7e0292a7..12753002af67eb411aa7e475b2cff2753b942bac 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -30,9 +30,11 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 
 /**
  * TestingScheduledThreadPool exports 2 interfaces: <br>
- * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
+ * {@link org.opendaylight.controller.config.manager.testingservices
+ * .scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
  * ,<br>
- * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME}
+ * {@link org.opendaylight.controller.config.manager
+ * .testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME}
  * <br>
  * <br>
  * It also exports 2 runtime beans, one default and one with additional
@@ -40,25 +42,21 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
  */
 public class RuntimeBeanTest extends AbstractScheduledTest {
 
-    ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(
-            TestingScheduledThreadPoolModuleFactory.NAME, scheduled1,
-            Maps.<String, String> newHashMap());
+    ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
+            SCHEDULED1, Maps.<String, String>newHashMap());
     // additional runtime bean
-    ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(
-            TestingScheduledThreadPoolModuleFactory.NAME, scheduled1,
-            ImmutableMap.of("a", "b"));
+    ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
+            SCHEDULED1, ImmutableMap.of("a", "b"));
 
-    List<ObjectName> allObjectNames = Lists.newArrayList(ifc1runtimeON1,
-            ifc1runtimeON2);
+    List<ObjectName> allObjectNames = Lists.newArrayList(ifc1runtimeON1, ifc1runtimeON2);
 
-    private ObjectName createScheduled() throws InstanceAlreadyExistsException,
-            ConflictingVersionException, ValidationException {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+    private ObjectName createScheduled()
+            throws InstanceAlreadyExistsException, ConflictingVersionException, ValidationException {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
         // create using TestingThreadPoolIfc:
-        ObjectName createdConfigBean = transaction.createModule(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+        ObjectName createdConfigBean = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
+                SCHEDULED1);
         // commit
         transaction.commit();
         return createdConfigBean;
@@ -93,27 +91,21 @@ public class RuntimeBeanTest extends AbstractScheduledTest {
     @Test
     public void testLookup() throws Exception {
         createScheduled();
-        assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2),
-                configRegistryClient.lookupRuntimeBeans());
+        assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2), configRegistryClient.lookupRuntimeBeans());
     }
 
     @Test
     public void testReuse() throws Exception {
         ObjectName createdConfigBean = createScheduled();
         // empty transaction
-        CommitStatus commitInfo = configRegistryClient.createTransaction()
-                .commit();
+        CommitStatus commitInfo = configRegistryClient.createTransaction().commit();
 
         // check that it was reused
-        ObjectName readableConfigBean = ObjectNameUtil
-                .withoutTransactionName(createdConfigBean);
-        List<ObjectName> newInstances = Collections.<ObjectName> emptyList();
-        List<ObjectName> reusedInstances = Lists
-                .newArrayList(readableConfigBean);
-        List<ObjectName> recreatedInstaces = Collections
-                .<ObjectName> emptyList();
-        assertEquals(new CommitStatus(newInstances, reusedInstances,
-                recreatedInstaces), commitInfo);
+        ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
+        List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
+        List<ObjectName> reusedInstances = Lists.newArrayList(readableConfigBean);
+        List<ObjectName> recreatedInstaces = Collections.<ObjectName>emptyList();
+        assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
         checkRuntimeBeans();
     }
 
@@ -121,37 +113,31 @@ public class RuntimeBeanTest extends AbstractScheduledTest {
     public void testRecreate() throws Exception {
         ObjectName createdConfigBean = createScheduled();
         // empty transaction
-        ConfigTransactionJMXClient configTransaction = configRegistryClient
-                .createTransaction();
-        ObjectName scheduledWritableON = configTransaction.lookupConfigBean(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+        ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
+        ObjectName scheduledWritableON = configTransaction
+                .lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
         TestingScheduledThreadPoolConfigBeanMXBean scheduledWritableProxy = configTransaction
                 .newMXBeanProxy(scheduledWritableON, TestingScheduledThreadPoolConfigBeanMXBean.class);
         scheduledWritableProxy.setRecreate(true);
         CommitStatus commitInfo = configTransaction.commit();
         // check that it was recreated
-        ObjectName readableConfigBean = ObjectNameUtil
-                .withoutTransactionName(createdConfigBean);
-        List<ObjectName> newInstances = Collections.<ObjectName> emptyList();
-        List<ObjectName> reusedInstances = Collections.<ObjectName> emptyList();
-        List<ObjectName> recreatedInstaces = Lists
-                .newArrayList(readableConfigBean);
-        assertEquals(new CommitStatus(newInstances, reusedInstances,
-                recreatedInstaces), commitInfo);
+        ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
+        List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
+        List<ObjectName> reusedInstances = Collections.<ObjectName>emptyList();
+        List<ObjectName> recreatedInstaces = Lists.newArrayList(readableConfigBean);
+        assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
         checkRuntimeBeans();
     }
 
     @Test
     public void testDestroy_shouldUnregisterRuntimeBeans() throws Exception {
         ObjectName createdConfigBean = createScheduled();
-        ConfigTransactionJMXClient configTransaction = configRegistryClient
-                .createTransaction();
-        configTransaction.destroyModule(ObjectNameUtil
-                .createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean));
+        ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
+        configTransaction.destroyModule(
+                ObjectNameUtil.createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean));
         configTransaction.commit();
         for (ObjectName on : allObjectNames) {
             checkRuntimeBeanDoesNotExist(on);
         }
     }
-
 }
index 2a7876255fed3c1f6a492472cdd113b4c6de0b2f..9c6ba0700cba40081b6f9972ba5ee6f80f55747e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -31,24 +31,21 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 
 public class TwoInterfacesExportTest extends AbstractScheduledTest {
 
-    private void assertExists(final String moduleName, final String instanceName)
-            throws Exception {
+    private void assertExists(final String moduleName, final String instanceName) throws Exception {
         assertExists(null, moduleName, instanceName);
     }
 
-    private void assertExists(@Nullable final ConfigTransactionJMXClient transaction,
-            final String moduleName, final String instanceName)
-            throws InstanceNotFoundException, IntrospectionException, ReflectionException {
+    private void assertExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName,
+            final String instanceName) throws InstanceNotFoundException, IntrospectionException, ReflectionException {
         if (transaction != null) {
             transaction.lookupConfigBean(moduleName, instanceName);
             // make a dummy call
-            platformMBeanServer.getMBeanInfo(ObjectNameUtil.createTransactionModuleON(
-                    transaction.getTransactionName(), moduleName, instanceName));
+            platformMBeanServer.getMBeanInfo(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
+                    moduleName, instanceName));
         } else {
             configRegistryClient.lookupConfigBean(moduleName, instanceName);
             // make a dummy call
-            platformMBeanServer.getMBeanInfo(ObjectNameUtil.createReadOnlyModuleON(moduleName,
-                    instanceName));
+            platformMBeanServer.getMBeanInfo(ObjectNameUtil.createReadOnlyModuleON(moduleName, instanceName));
         }
     }
 
@@ -56,123 +53,105 @@ public class TwoInterfacesExportTest extends AbstractScheduledTest {
         assertNotExists(null, moduleName, instanceName);
     }
 
-    private void assertNotExists(
-            @Nullable final ConfigTransactionJMXClient transaction,
-            final String moduleName, final String instanceName) {
+    private void assertNotExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName,
+            final String instanceName) {
 
         if (transaction != null) {
             try {
                 transaction.lookupConfigBean(moduleName, instanceName);
                 fail();
             } catch (final InstanceNotFoundException e) {
-
+                // FIXME: should be empty?
             }
         } else {
             try {
                 configRegistryClient.lookupConfigBean(moduleName, instanceName);
                 fail();
             } catch (final InstanceNotFoundException e) {
-
+                // FIXME: should be empty?
             }
         }
     }
 
     @Test
     public void twoInterfaceNamesAfterCreatingConfigBean() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
         // create using TestingThreadPoolIfc:
-        ObjectName scheduled1name = transaction.createModule(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+        ObjectName scheduled1name = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
 
-        ObjectName retrievedName = transaction.lookupConfigBean(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+        ObjectName retrievedName = transaction.lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME,
+                SCHEDULED1);
         assertEquals(scheduled1name, retrievedName);
 
         // getExistingConfigBean should resolve moduleName
         String moduleName = TestingScheduledThreadPoolModuleFactory.NAME;
-        retrievedName = transaction.lookupConfigBean(moduleName, scheduled1);
-        ObjectName expected = ObjectNameUtil.createTransactionModuleON(
-                transaction.getTransactionName(), moduleName, scheduled1);
+        retrievedName = transaction.lookupConfigBean(moduleName, SCHEDULED1);
+        ObjectName expected = ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName,
+                SCHEDULED1);
         assertEquals(expected, retrievedName);
 
         // commit
         transaction.commit();
-        assertEquals(1, TestingScheduledThreadPoolImpl.allExecutors.size());
-        assertFalse(TestingScheduledThreadPoolImpl.allExecutors.get(0)
-                .isTerminated());
-        assertEquals(0,
-                TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
+        assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size());
+        assertFalse(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated());
+        assertEquals(0, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
 
-        assertExists(moduleName, scheduled1);
+        assertExists(moduleName, SCHEDULED1);
 
         // destroy using ThreadPool ifc
         transaction = configRegistryClient.createTransaction();
-        transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(
-                transaction.getTransactionName(), moduleName, scheduled1));
+        transaction.destroyModule(
+                ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName, SCHEDULED1));
         transaction.commit();
-        assertEquals(1, TestingScheduledThreadPoolImpl.allExecutors.size());
-        assertTrue(TestingScheduledThreadPoolImpl.allExecutors.get(0)
-                .isTerminated());
-        assertEquals(1,
-                TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
+        assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size());
+        assertTrue(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated());
+        assertEquals(1, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
 
         // should not be in platform:
 
-        assertNotExists(moduleName, scheduled1);
+        assertNotExists(moduleName, SCHEDULED1);
 
         transaction = configRegistryClient.createTransaction();
         // should not be in transaction
-        assertNotExists(transaction, moduleName, scheduled1);
+        assertNotExists(transaction, moduleName, SCHEDULED1);
     }
 
     @Test
-    public void tryToRegisterThreadPoolWithSameName()
-            throws InstanceAlreadyExistsException {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+    public void tryToRegisterThreadPoolWithSameName() throws InstanceAlreadyExistsException {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
-        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
-                scheduled1);
+        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
         try {
-            transaction.createModule(
-                    TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+            transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
             fail();
         } catch (final InstanceAlreadyExistsException e) {
-            assertThat(
-                    e.getMessage(),
-                    containsString("There is an instance registered with name ModuleIdentifier{factoryName='scheduled', instanceName='scheduled1'}"));
+            assertThat(e.getMessage(), containsString(
+                    "There is an instance registered with name "
+                    + "ModuleIdentifier{factoryName='scheduled', instanceName='scheduled1'}"));
         }
     }
 
     // --
     @Test
     public void testRegisteringAllIfcNames() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
-                scheduled1);
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
         transaction.commit();
-        assertExists(TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+        assertExists(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
         // another transaction
         transaction = configRegistryClient.createTransaction();
-        assertExists(transaction, TestingScheduledThreadPoolModuleFactory.NAME,
-                scheduled1);
+        assertExists(transaction, TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
     }
 
     @Test
-    public void testWithAPSP_useScheduledNames()
-            throws InstanceAlreadyExistsException, ValidationException {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        ObjectName scheduledName = transaction.createModule(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
-
-        ObjectName apspName = transaction.createModule(
-                TestingParallelAPSPModuleFactory.NAME, "apsp1");
-        TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(
-                apspName, TestingParallelAPSPConfigMXBean.class);
+    public void testWithAPSP_useScheduledNames() throws InstanceAlreadyExistsException, ValidationException {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName scheduledName = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
+
+        ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1");
+        TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName,
+                TestingParallelAPSPConfigMXBean.class);
         apspProxy.setThreadPool(scheduledName);
         apspProxy.setSomeParam("someParam");
         transaction.validateConfig();
@@ -181,17 +160,14 @@ public class TwoInterfacesExportTest extends AbstractScheduledTest {
 
     @Test
     public void testWithAPSP_useIfcNameMismatch() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
-                scheduled1);
-
-        ObjectName apspName = transaction.createModule(
-                TestingParallelAPSPModuleFactory.NAME, "apsp1");
-        TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(
-                apspName, TestingParallelAPSPConfigMXBean.class);
-        apspProxy.setThreadPool(ObjectNameUtil.createReadOnlyModuleON(
-                TestingScheduledThreadPoolModuleFactory.NAME, scheduled1));
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
+
+        ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1");
+        TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName,
+                TestingParallelAPSPConfigMXBean.class);
+        apspProxy.setThreadPool(
+                ObjectNameUtil.createReadOnlyModuleON(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1));
         apspProxy.setSomeParam("someParam");
         transaction.validateConfig();
         transaction.commit();
index 5c30d1e977fafbed51ba19c87e4027ec67d87bd1..b87f3cd077ed3959b6686ae881a39d35fcfa3cb8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -10,8 +10,8 @@ package org.opendaylight.controller.config.manager.testingservices.seviceinterfa
 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingModifiableThreadPoolIfc;
 
-@ServiceInterfaceAnnotation(value = "fqn:modifiable-threadpool", osgiRegistrationType = TestingModifiableThreadPoolIfc.class,
-        namespace = "foo",  revision = "bar", localName = "modifiable-threadpool")
-public interface ModifiableThreadPoolServiceInterface extends
-        TestingThreadPoolServiceInterface {
+@ServiceInterfaceAnnotation(value = "fqn:modifiable-threadpool",
+    osgiRegistrationType = TestingModifiableThreadPoolIfc.class,
+    namespace = "foo", revision = "bar", localName = "modifiable-threadpool")
+public interface ModifiableThreadPoolServiceInterface extends TestingThreadPoolServiceInterface {
 }
index 2d99b25e0af5c5383f6b4cede90753100d406355..66fdf301d35af914bd8a57b3c3bb802e0925778d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -11,9 +11,9 @@ import org.opendaylight.controller.config.api.annotations.AbstractServiceInterfa
 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
 
-@ServiceInterfaceAnnotation(value = TestingThreadPoolServiceInterface.QNAME, osgiRegistrationType = TestingThreadPoolIfc.class,
+@ServiceInterfaceAnnotation(value = TestingThreadPoolServiceInterface.QNAME,
+    osgiRegistrationType = TestingThreadPoolIfc.class,
     namespace = "ns", revision = "foo", localName = "testing-threadpool")
-public interface TestingThreadPoolServiceInterface extends
-        AbstractServiceInterface {
+public interface TestingThreadPoolServiceInterface extends AbstractServiceInterface {
     String QNAME = "(ns?revision=foo)testing-threadpool";
 }
index 4f8de6dfe16f20467f5b8cbb56ff0d004be4a755..35413a1b1fcc23541cf60b719d1386a5ece20324 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -26,14 +26,14 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
     private final String uniqueName;
 
     public static void cleanUp() {
-        for (ExecutorService executorService : allExecutors) {
+        for (ExecutorService executorService : ALL_EXECUTORS) {
             executorService.shutdown();
         }
-        allExecutors.clear();
+        ALL_EXECUTORS.clear();
     }
 
     // for verification purposes:
-    public static final List<ThreadPoolExecutor> allExecutors = Collections
+    public static final List<ThreadPoolExecutor> ALL_EXECUTORS = Collections
             .synchronizedList(Lists.<ThreadPoolExecutor>newLinkedList());
 
     public TestingFixedThreadPool(final int threadCount, final String uniqueName) {
@@ -41,7 +41,7 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
         this.uniqueName = uniqueName;
         executorService = (ThreadPoolExecutor) Executors
                 .newFixedThreadPool(threadCount);
-        allExecutors.add(executorService);
+        ALL_EXECUTORS.add(executorService);
     }
 
     @Override
@@ -52,7 +52,7 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
     @Override
     public void close() throws IOException {
         executorService.shutdown();
-        allExecutors.remove(executorService);
+        ALL_EXECUTORS.remove(executorService);
 
     }
 
@@ -70,5 +70,4 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
         checkArgument(activeCount > 0);
         executorService.setMaximumPoolSize(activeCount);
     }
-
 }
index a6c9b59605b35f7bbbaf9c9c37cd6c919cfbae6e..8ac0c322231b8d29ed9213b4090280e9ba07d366 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -35,7 +35,6 @@ public class TestingFixedThreadPoolModule implements
         this.oldInstance = oldInstance;
     }
 
-
     // attributes
     @Override
     public void setThreadCount(final int threadCount) {
@@ -75,6 +74,7 @@ public class TestingFixedThreadPoolModule implements
     }
 
     @Override
+    @SuppressWarnings("IllegalCatch")
     public Closeable getInstance() {
         if (instance == null) {
             if (isReusable() && triggerNewInstanceCreation == false) { // simulate
index e78ae980096fa5e8905e12bf0f83de330b353376..5975ce141ecf91b4b49da307041f1829c51f11a6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -21,10 +21,11 @@ import org.opendaylight.controller.config.spi.Module;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.osgi.framework.BundleContext;
 
-public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory implements ModuleFactory {
+public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory
+        implements ModuleFactory {
     public static final String NAME = "fixed";
 
-    private static final Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
+    private static final Set<Class<? extends AbstractServiceInterface>> IFC = ImmutableSet.of(
             (Class<? extends AbstractServiceInterface>) ModifiableThreadPoolServiceInterface.class,
             TestingThreadPoolServiceInterface.class);
 
@@ -36,14 +37,12 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr
     @Override
     public TestingFixedThreadPoolModule createModule(final String instanceName,
             final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME,
-                instanceName), null, null);
+        return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null);
     }
 
     @Override
-    public Module createModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
-            throws Exception {
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+            final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
         int threadCount = (Integer) old.getAttribute("ThreadCount");
         // is the instance compatible?
         TestingFixedThreadPool oldInstance;
@@ -54,9 +53,8 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr
             // old instance will be closed, new needs to be created
             oldInstance = null;
         }
-        TestingFixedThreadPoolModule result = new TestingFixedThreadPoolModule(
-                new ModuleIdentifier(NAME, instanceName), old.getInstance(),
-                oldInstance);
+        TestingFixedThreadPoolModule result = new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName),
+                old.getInstance(), oldInstance);
         result.setThreadCount(threadCount);
         return result;
     }
@@ -64,16 +62,17 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr
     @Override
     public boolean isModuleImplementingServiceInterface(
             final Class<? extends AbstractServiceInterface> serviceInterface) {
-        return ifc.contains(serviceInterface);
+        return IFC.contains(serviceInterface);
     }
 
     @Override
-    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+    public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+            final BundleContext bundleContext) {
         return new HashSet<>();
     }
 
     @Override
     public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
-        return ifc;
+        return IFC;
     }
 }
index bd75a703d7efd5d62bcc37a33e7099d306efce18..dc1bdf4b02719bf0014136fee3a2004ad97d680d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -7,7 +7,8 @@
  */
 /**
  * Represents simple service that has getters and setters, but no dependencies.
- * Creates fixed thread pool wrapped in {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
+ * Creates fixed thread pool wrapped in {@link org.opendaylight
+ * .controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
  * Supports changing the number of threads on 'live' executor.
  */
 package org.opendaylight.controller.config.manager.testingservices.threadpool;
index e047a1eccae5452d4fba1f481012c619a5b6192d..9198c4b8a984417665852da96c8e9410d4069430 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -29,7 +29,8 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 import org.osgi.framework.BundleContext;
 
 public class ShutdownTest extends AbstractConfigTest {
-    private final TestingFixedThreadPoolModuleFactory testingFixedThreadPoolModuleFactory = new TestingFixedThreadPoolModuleFactory();
+    private final TestingFixedThreadPoolModuleFactory testingFixedThreadPoolModuleFactory =
+            new TestingFixedThreadPoolModuleFactory();
 
     @Mock
     ModuleFactoriesResolver mockedResolver;
@@ -44,7 +45,6 @@ public class ShutdownTest extends AbstractConfigTest {
         super.initConfigTransactionManagerImpl(mockedResolver);
     }
 
-
     @Test
     public void testCreateAndDestroyBeanInSameTransaction() throws Exception {
         {
@@ -52,12 +52,12 @@ public class ShutdownTest extends AbstractConfigTest {
             SimpleConfigurationTest.createFixedThreadPool(transaction);
             transaction.commit();
         }
-        assertEquals(1, TestingFixedThreadPool.allExecutors.size());
+        assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
         doReturn(Collections.emptyMap()).when(mockedResolver).getAllFactories();
         {
             ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
             transaction.commit();
         }
-        assertEquals(1, TestingFixedThreadPool.allExecutors.size());
+        assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
     }
 }
index d837ffcdb481ade6eb41c7182b521c20232c08d5..f2dc012bc84b8c2c2eaf2ed6a7d3050babb80c7c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -22,6 +22,7 @@ import java.util.Set;
 import java.util.concurrent.ThreadPoolExecutor;
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.InstanceNotFoundException;
+import javax.management.IntrospectionException;
 import javax.management.MBeanException;
 import javax.management.ObjectName;
 import javax.management.ReflectionException;
@@ -55,20 +56,18 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
  * dependencies.
  */
 public class SimpleConfigurationTest extends AbstractConfigTest {
-    private static final int numberOfThreads = 5;
-    private final int numberOfThreads2 = 10;
-    private static final String fixed1 = "fixed1";
-    private static final List<ObjectName> emptyONs = Collections
-            .<ObjectName> emptyList();
-    private static final ObjectName platformFixed1ON = ObjectNameUtil
-            .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, fixed1);
-    private static final List<ObjectName> fixed1List = Arrays
-            .asList(platformFixed1ON);
+    private static final int NUMBER_OF_THREADS = 5;
+    private static final int NUMBER_OF_THREADS2 = 10;
+    private static final String FIXED1 = "fixed1";
+    private static final List<ObjectName> EMPTYO_NS = Collections.<ObjectName>emptyList();
+    private static final ObjectName PLATFORM_FIXED1ON = ObjectNameUtil
+            .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
+    private static final List<ObjectName> FIXED1_LIST = Arrays.asList(PLATFORM_FIXED1ON);
 
     @Before
     public void setUp() {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
-                new TestingFixedThreadPoolModuleFactory()));
+        super.initConfigTransactionManagerImpl(
+                new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory()));
     }
 
     @After
@@ -77,8 +76,7 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
     }
 
     private ObjectName firstCommit() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
         ObjectName fixed1names = createFixedThreadPool(transaction);
 
@@ -86,36 +84,32 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
         assertEquals(1, configRegistryClient.getOpenConfigs().size());
         CommitStatus commitStatus = transaction.commit();
         assertEquals(0, configRegistryClient.getOpenConfigs().size());
-        CommitStatus expected = new CommitStatus(Arrays.asList(ObjectNameUtil
-                .withoutTransactionName(fixed1names)), emptyONs, emptyONs);
+        CommitStatus expected = new CommitStatus(Arrays.asList(ObjectNameUtil.withoutTransactionName(fixed1names)),
+                EMPTYO_NS, EMPTYO_NS);
         assertEquals(expected, commitStatus);
 
-        assertEquals(1, TestingFixedThreadPool.allExecutors.size());
-        assertFalse(TestingFixedThreadPool.allExecutors.get(0).isShutdown());
+        assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
+        assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown());
         return fixed1names;
     }
 
-    static ObjectName createFixedThreadPool(
-            final ConfigTransactionJMXClient transaction)
+    static ObjectName createFixedThreadPool(final ConfigTransactionJMXClient transaction)
             throws InstanceAlreadyExistsException, InstanceNotFoundException {
         transaction.assertVersion(0, 1);
 
-        ObjectName fixed1names = transaction.createModule(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
-        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction
-                .newMXBeanProxy(fixed1names, TestingFixedThreadPoolConfigMXBean.class);
-        fixedConfigProxy.setThreadCount(numberOfThreads);
+        ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
+        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1names,
+                TestingFixedThreadPoolConfigMXBean.class);
+        fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS);
 
-        ObjectName retrievedNames = transaction.lookupConfigBean(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
+        ObjectName retrievedNames = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
         assertEquals(fixed1names, retrievedNames);
         return fixed1names;
     }
 
     @Test
     public void testCreateAndDestroyBeanInSameTransaction() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         ObjectName fixed1names = createFixedThreadPool(transaction);
         transaction.destroyModule(fixed1names);
         CommitStatus commitStatus = transaction.commit();
@@ -125,21 +119,16 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
 
     @Test
     public void testValidationUsingJMXClient() throws Exception {
-        ConfigTransactionClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionClient transaction = configRegistryClient.createTransaction();
         testValidation(transaction);
     }
 
-
-    private static void testValidation(final ConfigTransactionClient transaction)
-            throws InstanceAlreadyExistsException, ReflectionException,
-            InstanceNotFoundException, MBeanException, ConflictingVersionException {
-        ObjectName fixed1names = transaction.createModule(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
+    private static void testValidation(final ConfigTransactionClient transaction) throws InstanceAlreadyExistsException,
+            ReflectionException, InstanceNotFoundException, MBeanException, ConflictingVersionException {
+        ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
         // call validate on config bean
         try {
-            platformMBeanServer.invoke(fixed1names, "validate", new Object[0],
-                    new String[0]);
+            platformMBeanServer.invoke(fixed1names, "validate", new Object[0], new String[0]);
             fail();
         } catch (final MBeanException e) {
             Exception targetException = e.getTargetException();
@@ -152,13 +141,10 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
             transaction.validateBean(fixed1names);
             fail();
         } catch (final ValidationException e) {
-            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
-                    .getFailedValidations().entrySet()) {
-                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
-                        .getValue().entrySet()) {
-                    assertEquals(
-                            "Parameter 'threadCount' must be greater than 0",
-                            entry.getValue().getMessage());
+            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+                    .entrySet()) {
+                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+                    assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
                 }
             }
         }
@@ -167,26 +153,20 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
             transaction.validateConfig();
             fail();
         } catch (final ValidationException e) {
-            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
-                    .getFailedValidations().entrySet()) {
-                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
-                        .getValue().entrySet()) {
-                    assertEquals(
-                            "Parameter 'threadCount' must be greater than 0",
-                            entry.getValue().getMessage());
+            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+                    .entrySet()) {
+                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+                    assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
                 }
             }
         }
         try {
             transaction.commit();
         } catch (final ValidationException e) {
-            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
-                    .getFailedValidations().entrySet()) {
-                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
-                        .getValue().entrySet()) {
-                    assertEquals(
-                            "Parameter 'threadCount' must be greater than 0",
-                            entry.getValue().getMessage());
+            for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+                    .entrySet()) {
+                for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+                    assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
                 }
             }
         }
@@ -195,14 +175,13 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
     @Test
     public void test_createThreadPool_changeNumberOfThreads() throws Exception {
         firstCommit();
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction);
-        assertEquals(numberOfThreads, fixedConfigProxy.getThreadCount());
-        fixedConfigProxy.setThreadCount(numberOfThreads2);
+        assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount());
+        fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2);
         CommitStatus commitStatus = transaction.commit();
-        checkThreadPools(1, numberOfThreads2);
-        CommitStatus expected = new CommitStatus(emptyONs, fixed1List, emptyONs);
+        checkThreadPools(1, NUMBER_OF_THREADS2);
+        CommitStatus expected = new CommitStatus(EMPTYO_NS, FIXED1_LIST, EMPTYO_NS);
         assertEquals(expected, commitStatus);
     }
 
@@ -214,42 +193,39 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
         // 2, check that configuration was copied to platform
         ObjectName on = ObjectNameUtil.withoutTransactionName(fixed1name);
         platformMBeanServer.getMBeanInfo(on);
-        assertEquals(numberOfThreads, platformMBeanServer.getAttribute(on, "ThreadCount"));
+        assertEquals(NUMBER_OF_THREADS, platformMBeanServer.getAttribute(on, "ThreadCount"));
 
         // 3, shutdown fixed1 in new transaction
-        assertFalse(TestingFixedThreadPool.allExecutors.get(0).isShutdown());
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown());
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
         // check versions
         transaction.assertVersion(1, 2);
 
         // test that it was copied to new transaction
-        ObjectName retrievedName = transaction.lookupConfigBean(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
+        ObjectName retrievedName = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
         assertNotNull(retrievedName);
 
         // check that number of threads was copied from dynamic
 
-        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction
-                .newMXBeanProxy(retrievedName, TestingFixedThreadPoolConfigMXBean.class);
-        assertEquals(numberOfThreads, fixedConfigProxy.getThreadCount());
+        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(retrievedName,
+                TestingFixedThreadPoolConfigMXBean.class);
+        assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount());
 
         // destroy
-        transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(
-                transaction.getTransactionName(),
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1));
+        transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
+                TestingFixedThreadPoolModuleFactory.NAME, FIXED1));
         transaction.commit();
 
         // 4, check
         assertEquals(2, configRegistryClient.getVersion());
-        assertEquals(0, TestingFixedThreadPool.allExecutors.size());
+        assertEquals(0, TestingFixedThreadPool.ALL_EXECUTORS.size());
 
         // dynamic config should be removed from platform
         try {
             platformMBeanServer.getMBeanInfo(on);
             fail();
-        } catch (final Exception e) {
+        } catch (final ReflectionException | InstanceNotFoundException | IntrospectionException e) {
             assertTrue(e instanceof InstanceNotFoundException);
         }
     }
@@ -259,36 +235,30 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
         // 1, start transaction, create new fixed thread pool
         firstCommit();
         // destroy and recreate with different # of threads
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-
-        transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(
-                transaction.getTransactionName(),
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1));
-
-        ObjectName fixed1name = transaction.createModule(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
-        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction
-                .newMXBeanProxy(fixed1name, TestingFixedThreadPoolConfigMXBean.class);
-        fixedConfigProxy.setThreadCount(numberOfThreads2);
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+
+        transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
+                TestingFixedThreadPoolModuleFactory.NAME, FIXED1));
+
+        ObjectName fixed1name = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
+        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name,
+                TestingFixedThreadPoolConfigMXBean.class);
+        fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2);
         // commit
         transaction.commit();
         // check that first threadpool is closed
-        checkThreadPools(1, numberOfThreads2);
+        checkThreadPools(1, NUMBER_OF_THREADS2);
     }
 
     private static void checkThreadPools(final int expectedTotalNumberOfExecutors,
             final int expectedNumberOfThreadsInLastExecutor) {
-        assertEquals(expectedTotalNumberOfExecutors,
-                TestingFixedThreadPool.allExecutors.size());
+        assertEquals(expectedTotalNumberOfExecutors, TestingFixedThreadPool.ALL_EXECUTORS.size());
         for (int i = 0; i < expectedTotalNumberOfExecutors - 1; i++) {
-            assertTrue(TestingFixedThreadPool.allExecutors.get(i).isShutdown());
+            assertTrue(TestingFixedThreadPool.ALL_EXECUTORS.get(i).isShutdown());
         }
-        ThreadPoolExecutor lastExecutor = TestingFixedThreadPool.allExecutors
-                .get(expectedTotalNumberOfExecutors - 1);
+        ThreadPoolExecutor lastExecutor = TestingFixedThreadPool.ALL_EXECUTORS.get(expectedTotalNumberOfExecutors - 1);
         assertFalse(lastExecutor.isShutdown());
-        assertEquals(expectedNumberOfThreadsInLastExecutor,
-                lastExecutor.getMaximumPoolSize());
+        assertEquals(expectedNumberOfThreadsInLastExecutor, lastExecutor.getMaximumPoolSize());
     }
 
     @Test
@@ -296,34 +266,31 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
         // 1, start transaction, create new fixed thread pool
         firstCommit();
         // switch boolean to create new instance
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction);
 
         fixedConfigProxy.setTriggerNewInstanceCreation(true);
         // commit
         CommitStatus commitStatus = transaction.commit();
         // check that new threadpool is created and old one is closed
-        checkThreadPools(1, numberOfThreads);
-        CommitStatus expected = new CommitStatus(emptyONs, emptyONs, fixed1List);
+        checkThreadPools(1, NUMBER_OF_THREADS);
+        CommitStatus expected = new CommitStatus(EMPTYO_NS, EMPTYO_NS, FIXED1_LIST);
         assertEquals(expected, commitStatus);
     }
 
     // return MBeanProxy for 'fixed1' and current transaction
     private static TestingFixedThreadPoolConfigMXBean startReconfiguringFixed1ThreadPool(
             final ConfigTransactionJMXClient transaction) throws InstanceNotFoundException {
-        ObjectName fixed1name = transaction.lookupConfigBean(
-                TestingFixedThreadPoolModuleFactory.NAME, fixed1);
+        ObjectName fixed1name = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
 
-        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction
-                .newMXBeanProxy(fixed1name, TestingFixedThreadPoolConfigMXBean.class);
+        TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name,
+                TestingFixedThreadPoolConfigMXBean.class);
         return fixedConfigProxy;
     }
 
     @Test
     public void testAbort() throws Exception {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         assertEquals(1, configRegistryClient.getOpenConfigs().size());
 
         transaction.abortConfig();
@@ -331,48 +298,40 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
         try {
             platformMBeanServer.getMBeanInfo(transaction.getObjectName());
             fail();
-        }catch(final InstanceNotFoundException e){
-            assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction", e.getMessage());
+        } catch (final InstanceNotFoundException e) {
+            assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction",
+                    e.getMessage());
         }
     }
 
     @Test
     public void testOptimisticLock_ConfigTransactionClient() throws Exception {
-        ConfigTransactionJMXClient transaction1 = configRegistryClient
-                .createTransaction();
-        ConfigTransactionJMXClient transaction2 = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
+        ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
         transaction2.assertVersion(0, 2);
         transaction2.commit();
         try {
             transaction1.commit();
             fail();
         } catch (final ConflictingVersionException e) {
-            assertEquals(
-                    "Optimistic lock failed. Expected parent version 2, was 0",
-                    e.getMessage());
+            assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
         }
     }
 
     @Test
     public void testOptimisticLock_ConfigRegistry() throws Exception {
-        ConfigTransactionJMXClient transaction1 = configRegistryClient
-                .createTransaction();
-        ConfigTransactionJMXClient transaction2 = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
+        ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
         transaction2.assertVersion(0, 2);
         transaction2.commit();
         try {
             configRegistryClient.commitConfig(transaction1.getObjectName());
             fail();
         } catch (final ConflictingVersionException e) {
-            assertEquals(
-                    "Optimistic lock failed. Expected parent version 2, was 0",
-                    e.getMessage());
+            assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
         }
     }
 
-
     @Test
     public void testQNames() {
         Set<String> availableModuleFactoryQNames = configRegistryClient.getAvailableModuleFactoryQNames();
@@ -380,5 +339,4 @@ public class SimpleConfigurationTest extends AbstractConfigTest {
 
         assertEquals(Sets.newHashSet(expected), availableModuleFactoryQNames);
     }
-
 }