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 b3d68c0..f1483b3 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 ae78c83..eb7fd38 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 dd6ccde..41e2b5b 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 bc8b6a5..827646f 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 7a1a74e..25b691f 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 b35c1dc..dd506af 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 11e5bfc..5b7ecb9 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 4780f96..f9a5acf 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 af58dd2..cad98b3 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 a64d8c3..fa263bc 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 4c5e391..288f2ac 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 2b7e262..51cef4d 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 5fc5182..ac056a8 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 8fa7fdf..e69aa86 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 ef4aadd..ada8a17 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 d449e28..6f4ed63 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 3a58b01..e8a6d51 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 cfe7ea1..1132f99 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 638165a..e5bb549 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 e4a4277..f9548ae 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 11d421c..ff607d3 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 1a43d6f..f768731 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 90cc623..1ac299b 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 63be03f..e07d0d7 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 7d0bee2..f4b326e 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 1492d5d..a4fcdbb 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 1f29a65..e84d2ee 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 9388b8e..88646b4 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 e9db071..5dc3fe2 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 ff504da..9031f23 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 8ec44a1..2649b14 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 1926c6b..28f512d 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 eba7ad1..d1c3d76 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 5841acf..132005a 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 5e70625..e89d6c8 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 472510f..6cf8315 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 169d1e6..71fcd58 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 fcde347..9871a04 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 8538e3f..059ba45 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 1fa97ac..e1c73df 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 {