From 2b78ca93f44c372fd72927db6cbd65f5d8387b49 Mon Sep 17 00:00:00 2001 From: David Suarez Date: Thu, 7 Sep 2017 11:18:53 +0200 Subject: [PATCH] Fix checkstyle issues to enforce it Fix checkstyle issues to enforce it. Change-Id: I306255919cdfe43208d7c254f2f6455f4126b92f Signed-off-by: David Suarez --- opendaylight/config/config-manager/pom.xml | 14 +- .../config/manager/impl/CommitInfo.java | 13 +- .../manager/impl/ConfigRegistryImpl.java | 450 +++++++++--------- .../impl/ConfigRegistryImplMXBean.java | 5 +- .../impl/ConfigTransactionControllerImpl.java | 218 ++++----- ...ConfigTransactionControllerImplMXBean.java | 10 +- .../ConfigTransactionControllerInternal.java | 57 +-- .../impl/ConfigTransactionLookupRegistry.java | 56 +-- .../config/manager/impl/DeadlockMonitor.java | 23 +- .../manager/impl/ModuleInternalInfo.java | 30 +- ...hableServiceReferenceWritableRegistry.java | 18 +- .../impl/ServiceReferenceRegistryImpl.java | 255 ++++++---- .../manager/impl/TransactionIdentifier.java | 10 +- .../DependencyResolverImpl.java | 138 +++--- .../DependencyResolverManager.java | 75 ++- .../dependencyresolver/DestroyedModule.java | 9 +- .../ModuleInternalTransactionalInfo.java | 6 +- .../dependencyresolver/ModulesHolder.java | 63 +-- .../dynamicmbean/AbstractDynamicWrapper.java | 177 +++---- .../impl/dynamicmbean/AnnotationsHelper.java | 33 +- .../impl/dynamicmbean/AttributeHolder.java | 55 +-- .../dynamicmbean/DynamicReadableWrapper.java | 8 +- .../dynamicmbean/DynamicWritableWrapper.java | 45 +- ...ierarchicalConfigMBeanFactoriesHolder.java | 16 +- .../impl/jmx/InternalJMXRegistrator.java | 7 +- .../impl/jmx/JMXNotifierConfigRegistry.java | 29 +- .../jmx/RootRuntimeBeanRegistratorImpl.java | 22 +- .../manager/impl/jmx/ServiceReference.java | 16 +- .../impl/jmx/ServiceReferenceRegistrator.java | 23 +- .../impl/osgi/BeanToOsgiServiceManager.java | 52 +- .../osgi/BlankTransactionServiceTracker.java | 22 +- ...eContextBackedModuleFactoriesResolver.java | 19 +- .../impl/osgi/ConfigManagerActivator.java | 43 +- .../impl/osgi/ExtensibleBundleTracker.java | 66 ++- .../impl/osgi/ModuleFactoryBundleTracker.java | 34 +- .../osgi/mapping/BindingContextProvider.java | 11 +- .../osgi/mapping/ModuleInfoBundleTracker.java | 21 +- .../RefreshingSCPModuleInfoRegistry.java | 41 +- .../manager/impl/util/InterfacesHelper.java | 66 +-- .../manager/impl/util/ModuleQNameUtil.java | 7 +- .../impl/util/OsgiRegistrationUtil.java | 10 +- .../manager/ConfigRegistryImplTest.java | 24 +- .../manager/impl/AbstractConfigTest.java | 115 +++-- ...AbstractLockedPlatformMBeanServerTest.java | 11 +- .../manager/impl/AbstractMockedModule.java | 14 +- .../manager/impl/ClassBasedModuleFactory.java | 57 +-- .../impl/ConfigRegistryImplLookupTest.java | 101 ++-- .../ConfigTransactionControllerImplTest.java | 85 ++-- .../ConfigTransactionManagerImplTest.java | 5 +- .../ServiceReferenceRegistryImplTest.java | 45 +- .../DependencyResolverManagerTest.java | 33 +- .../AbstractDynamicWrapperTest.java | 52 +- .../impl/dynamicmbean/AnnotationsTest.java | 83 ++-- .../DynamicWritableWrapperTest.java | 56 +-- .../HardcodedModuleFactoriesResolver.java | 30 +- .../BlankTransactionServiceTrackerTest.java | 5 +- ...textBackedModuleFactoriesResolverTest.java | 3 +- .../osgi/ModuleFactoryBundleTrackerTest.java | 33 +- .../RefreshingSCPModuleInfoRegistryTest.java | 12 +- .../RuntimeBeanRegistratorImplTest.java | 53 +-- .../impl/util/InterfacesHelperTest.java | 37 +- .../impl/util/OsgiRegistrationUtilTest.java | 8 +- .../TestingParallelAPSPConfigMXBean.java | 10 +- .../parallelapsp/TestingParallelAPSPImpl.java | 9 +- .../TestingParallelAPSPModule.java | 55 +-- .../TestingParallelAPSPModuleFactory.java | 17 +- .../test/DependentWiringTest.java | 67 ++- .../TestingScheduledThreadPoolImpl.java | 22 +- .../TestingScheduledThreadPoolModule.java | 27 +- ...stingScheduledThreadPoolModuleFactory.java | 27 +- .../scheduledthreadpool/package-info.java | 6 +- .../test/AbstractScheduledTest.java | 4 +- .../test/RuntimeBeanTest.java | 80 ++-- .../test/TwoInterfacesExportTest.java | 134 +++--- .../ModifiableThreadPoolServiceInterface.java | 10 +- .../TestingThreadPoolServiceInterface.java | 8 +- .../threadpool/TestingFixedThreadPool.java | 13 +- .../TestingFixedThreadPoolModule.java | 4 +- .../TestingFixedThreadPoolModuleFactory.java | 27 +- .../threadpool/package-info.java | 5 +- .../threadpool/test/ShutdownTest.java | 10 +- .../test/SimpleConfigurationTest.java | 214 ++++----- 82 files changed, 1817 insertions(+), 2067 deletions(-) diff --git a/opendaylight/config/config-manager/pom.xml b/opendaylight/config/config-manager/pom.xml index b3d68c0b79..f1483b35c0 100644 --- a/opendaylight/config/config-manager/pom.xml +++ b/opendaylight/config/config-manager/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 org.opendaylight.controller @@ -22,7 +23,7 @@ guava - + org.opendaylight.mdsal mdsal-binding-generator-impl @@ -66,6 +67,13 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + org.apache.felix maven-bundle-plugin @@ -73,7 +81,7 @@ org.opendaylight.controller.config.manager.impl.osgi.ConfigManagerActivator org.opendaylight.controller.config.manager.*, - javax.annotation.*, + javax.annotation.*, diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java index ae78c83754..eb7fd380cf 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java @@ -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 destroyedFromPreviousTransactions, final Map 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 getDestroyedFromPreviousTransactions() { return destroyedFromPreviousTransactions; diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java index dd6ccde37e..41e2b5bf60 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java @@ -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 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> 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> transactions = transactionsHolder.getCurrentTransactions(); - Entry configTransactionControllerEntry = transactions.get(transactionName); + Map> transactions = + transactionsHolder.getCurrentTransactions(); + Entry 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 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 annotationMapping = configTransactionController.getWritableRegistry().findServiceInterfaces(moduleIdentifier); - BundleContext bc = configTransactionController.getModuleFactoryBundleContext( - entry.getModuleFactory().getImplementationName()); + Map 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 getOpenConfigs() { - Map> transactions = transactionsHolder - .getCurrentTransactions(); + Map> transactions = + transactionsHolder.getCurrentTransactions(); List result = new ArrayList<>(transactions.size()); - for (Entry configTransactionControllerEntry : transactions - .values()) { + for (Entry + 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> transactions = transactionsHolder - .getCurrentTransactions(); - for (Entry configTransactionControllerEntry : transactions - .values()) { - + Map> transactions = + transactionsHolder.getCurrentTransactions(); + for (Entry + 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 destroyedModules = currentConfig.getModulesToBeDestroyed(); LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size()); @@ -532,8 +519,7 @@ public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBe */ @Override public Set 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 lookupConfigBeans(final String moduleName, final String instanceName) { + ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName); + return baseJMXRegistrator.queryNames(namePattern, null); } /** * {@inheritDoc} */ @Override - public Set 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 lookupRuntimeBeans(final String moduleName, - final String instanceName) { + public Set 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> getServiceMapping() { - synchronized(readableSRRegistryLock) { + synchronized (readableSRRegistryLock) { return readableSRRegistry.getServiceMapping(); } } @Override public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - synchronized(readableSRRegistryLock) { + synchronized (readableSRRegistryLock) { return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); } } @Override public Set 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 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 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> 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> getCurrentTransactions() { + // first, remove closed transaction + for (Iterator>> + it = transactions.entrySet().iterator(); it.hasNext();) { + Entry> 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 currentConfig = new ConcurrentHashMap<>(); + + /** + * Add all modules to the internal map. Also add service instance to OSGi + * Service Registry. + */ + public void addAll(final Collection configInfos) { + if (!currentConfig.isEmpty()) { + throw new IllegalStateException("Error - some config entries were not removed: " + currentConfig); + } + for (ModuleInternalInfo configInfo : configInfos) { + add(configInfo); + } } - } - public Collection getEntries() { - return currentConfig.values(); - } - - public List getModulesToBeDestroyed() { - List 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 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> 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 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> getCurrentTransactions() { - // first, remove closed transaction - for (Iterator>> it = transactions - .entrySet().iterator(); it.hasNext(); ) { - Entry> entry = it - .next(); - if (entry.getValue().getKey().isClosed()) { - it.remove(); + public List getModulesToBeDestroyed() { + List result = new ArrayList<>(); + for (ModuleInternalInfo moduleInternalInfo : getEntries()) { + result.add(moduleInternalInfo.toDestroyedModule()); } + Collections.sort(result); + return result; } - return Collections.unmodifiableMap(transactions); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java index bc8b6a5288..827646f334 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java @@ -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(); diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java index 7a1a74e75f..25b691fc18 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java @@ -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 { +public class ConfigTransactionControllerImpl implements ConfigTransactionControllerInternal, + ConfigTransactionControllerImplMXBean, Identifiable { 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> currentlyRegisteredFactories, - final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer, - final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry writableSRRegistry) { + final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion, + final Map> 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 existingModules, final List lastListOfFactories) { + public void copyExistingModulesAndProcessFactoryDiff(final Collection existingModules, + final List lastListOfFactories) { // copy old configuration to this server for (ModuleInternalInfo oldConfigInfo : existingModules) { try { @@ -145,7 +142,8 @@ class ConfigTransactionControllerImpl implements Set 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 serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory); + final Set 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 modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory); for (ModuleIdentifier name : modulesOfRemovedFactory) { // remove service refs - final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name).getModuleFactory(); - final Set serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory); + final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name) + .getModuleFactory(); + final Set 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 collectedExceptions = new ArrayList<>(); - for (Entry entry : dependencyResolverManager - .getAllModules().entrySet()) { + for (Entry 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 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 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 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 lookupConfigBeans(final String moduleName, final String instanceName) { + return txLookupRegistry.lookupConfigBeans(moduleName, instanceName); } /** * {@inheritDoc} */ @Override - public Set 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 lookupRuntimeBeans(final String moduleName, - final String instanceName) { + public Set 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 factoryBundleContextEntry = this.currentlyRegisteredFactories.get(factoryName); + Map.Entry 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 lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { + public synchronized Map lookupServiceReferencesByServiceInterfaceName( + final String serviceInterfaceQName) { return writableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); } @Override - public synchronized Set lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException { + public synchronized Set 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); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java index b35c1dc7d0..dd506af74f 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java @@ -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(); - } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java index 11e5bfc63e..5b7ecb938c 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java @@ -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 entries, List lastListOfFactories); + void copyExistingModulesAndProcessFactoryDiff(Collection entries, + List 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 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(); diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java index 4780f96510..f9a5acffad 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java @@ -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> allCurrentFactories; + interface TransactionJMXRegistratorFactory { + TransactionJMXRegistrator create(); + } + ConfigTransactionLookupRegistry(final TransactionIdentifier transactionIdentifier, - final TransactionJMXRegistratorFactory factory, final Map> allCurrentFactories) { + final TransactionJMXRegistratorFactory factory, + final Map> 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 lookupConfigBeans(final String moduleName, final String instanceName) { + ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName, + transactionIdentifier.getName()); + return txModuleJMXRegistrator.queryNames(namePattern, null); } /** * {@inheritDoc} */ @Override - public Set 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 lookupRuntimeBeans(final String moduleName, - final String instanceName) { + public Set 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(); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java index af58dd2746..cad98b30f4 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java @@ -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 + '}'; } } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java index a64d8c33b8..fa263bc933 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java @@ -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, - Identifiable{ +public class ModuleInternalInfo implements Comparable, Identifiable { private final ModuleIdentifier name; // this registrator is passed to runtime bean registrator and config @@ -41,16 +40,14 @@ public class ModuleInternalInfo implements Comparable, 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, } /** + * 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, /** * 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); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java index 4c5e391f74..288f2ac669 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java @@ -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 findServiceInterfaces(ModuleIdentifier moduleIdentifier); - + Map findServiceInterfaces( + ModuleIdentifier moduleIdentifier); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java index 2b7e2622ba..51cef4d3ea 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java @@ -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 factories; private final Map> 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> namespacesToAnnotations; + private final Map> + namespacesToAnnotations; private final Map serviceQNamesToAnnotations; // all Service Interface qNames for sanity checking private final Set allQNames; - Map> modulesToServiceRef = new HashMap<>(); - + Map> modulesToServiceRef = + new HashMap<>(); // actual reference database private final Map refNames = new HashMap<>(); private final boolean writable; - private final Map> mBeans = new HashMap<>(); + private final Map> + managementBeans = new HashMap<>(); - private ServiceReferenceRegistryImpl(final Map factories, final LookupRegistry lookupRegistry, - final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, final boolean writable) { + private ServiceReferenceRegistryImpl(final Map 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 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 siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue()); - Set qNames = InterfacesHelper.getQNames(siAnnotations); + Set siAnnotations = InterfacesHelper + .getServiceInterfaceAnnotations(entry.getValue()); + Set 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> modifiableNamespacesToAnnotations = new HashMap<>(); - Map modifiableServiceQNamesToAnnotations = new HashMap<>(); + Map> + modifiableNamespacesToAnnotations = new HashMap<>(); + Map + modifiableServiceQNamesToAnnotations = new HashMap<>(); for (ServiceInterfaceAnnotation sia : allAnnotations) { - Map ofNamespace = - modifiableNamespacesToAnnotations.computeIfAbsent(sia.namespace(), k -> new HashMap<>()); + Map 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.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> currentlyRegisteredFactories) { + public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry( + final ServiceReferenceReadableRegistry oldReadableRegistry, + final ConfigTransactionLookupRegistry txLookupRegistry, + final Map> currentlyRegisteredFactories) { if (txLookupRegistry == null) { throw new IllegalArgumentException("txLookupRegistry is null"); } ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry; Map 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> refNameEntry : old.mBeans.entrySet()) { + private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry, + final String nullableDstTransactionName) { + for (Entry> + 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 extractFactoriesMap(final Map> currentlyRegisteredFactories) { + private static Map extractFactoriesMap( + final Map> currentlyRegisteredFactories) { Map result = new HashMap<>(); for (Entry> entry : currentlyRegisteredFactories.entrySet()) { result.put(entry.getKey(), entry.getValue().getKey()); @@ -243,8 +271,10 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public Map findServiceInterfaces(final ModuleIdentifier moduleIdentifier) { - Map result = modulesToServiceRef.get(moduleIdentifier); + public Map findServiceInterfaces( + final ModuleIdentifier moduleIdentifier) { + Map result = modulesToServiceRef + .get(moduleIdentifier); if (result == null) { return Collections.emptyMap(); } @@ -252,7 +282,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized Set lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException { + public synchronized Set 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> getServiceMapping() { + public synchronized Map> getServiceMapping() { Map> result = new HashMap<>(); - for (Entry entry: refNames.entrySet()) { - String qName = entry.getKey().getServiceInterfaceQName(); - Map innerMap = result.computeIfAbsent(qName, k -> new HashMap<>()); + for (Entry entry : refNames.entrySet()) { + String name = entry.getKey().getServiceInterfaceQName(); + Map 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 lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { + public synchronized Map lookupServiceReferencesByServiceInterfaceName( + final String serviceInterfaceQName) { Map> serviceMapping = getServiceMapping(); Map 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 mxBeanEntry = mBeans.get(serviceReference); + Entry 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 refNamesToAnnotations = - modulesToServiceRef.computeIfAbsent(moduleIdentifier, k -> new HashMap<>()); + Map 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 entry = mBeans.remove(serviceReference); + Entry 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 qNames) throws InstanceNotFoundException { + private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set names) + throws InstanceNotFoundException { ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE); assertWritable(); - Set serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, qNames); + Set serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names); for (ServiceReference sr : serviceReferencesLinkingTo) { removeServiceReference(sr); } return !serviceReferencesLinkingTo.isEmpty(); } - private Set findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set serviceInterfaceQNames) { + private Set findServiceReferencesLinkingTo(final ObjectName moduleObjectName, + final Set 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 diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java index 5fc5182db3..ac056a85ae 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java @@ -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; diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java index 8fa7fdfdde..e69aa8611a 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java @@ -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 { +public final class DependencyResolverImpl implements DependencyResolver, Comparable { 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 expectedServiceInterface, + public void validateDependency(final Class 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 resolveInstance(final Class 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 Class resolveIdentity(final IdentityAttributeRef identityRef, final Class 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) 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 void validateIdentity(final IdentityAttributeRef identityRef, final Class 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 chainForDetectingCycles) { + private static int getMaxDepth(final DependencyResolverImpl impl, final DependencyResolverManager manager, + final LinkedHashSet chainForDetectingCycles) { int maxDepth = 0; - final LinkedHashSet chainForDetectingCycles2 = new LinkedHashSet<>( - chainForDetectingCycles); + final LinkedHashSet 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); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java index ef4aaddf35..ada8a17532 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java @@ -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 moduleIdentifiersToDependencyResolverMap = new HashMap<>(); + private final Map + 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 getAllSorted() { transactionStatus.checkCommitStarted(); - List sorted = new ArrayList<>( - moduleIdentifiersToDependencyResolverMap.values()); + List sorted = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.values()); for (DependencyResolverImpl dri : sorted) { dri.countMaxDependencyDepth(this); } @@ -98,8 +97,7 @@ public class DependencyResolverManager implements DependencyResolverFactory, Aut } public List getSortedModuleIdentifiers() { - List result = new ArrayList<>( - moduleIdentifiersToDependencyResolverMap.size()); + List 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 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 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(); } - } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java index d449e28dfe..6f4ed6366a 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java @@ -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 diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java index 3a58b01b40..e8a6d512a4 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java @@ -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 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 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 getAllInfos(){ + public Collection 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(); diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java index 638165a46c..e5bb549492 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java @@ -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 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> 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 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> 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 attributeHolderMap, - final MBeanOperationInfo[] dOperations, final Set> jmxInterfaces) { + final Map attributeHolderMap, final MBeanOperationInfo[] operations, + final Set> jmxInterfaces) { - String dDescription = findDescription(module.getClass(), jmxInterfaces); - MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[0]; - List attributes = new ArrayList<>( - attributeHolderMap.size()); + String description = findDescription(module.getClass(), jmxInterfaces); + MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0]; + List 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> jmxInterfaces) { - List descriptions = AnnotationsHelper - .findClassAnnotationInSuperClassesAndIfcs(clazz, Description.class, jmxInterfaces); + List 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 buildMBeanInfo(final boolean writable, final ModuleIdentifier moduleIdentifier, - final Set> jmxInterfaces, - final ObjectName internalObjectName) { + final Set> jmxInterfaces, final ObjectName internalObjectName) { // internal variables for describing MBean elements Set 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 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)); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java index e4a427746d..f9548ae08e 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java @@ -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 * generic type of annotation * @return list of found annotations */ - static List findMethodAnnotationInSuperClassesAndIfcs( - final Method setter, final Class annotationType, - final Set> inspectedInterfaces) { + static List findMethodAnnotationInSuperClassesAndIfcs(final Method setter, + final Class annotationType, final Set> inspectedInterfaces) { Builder 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 List findClassAnnotationInSuperClassesAndIfcs( - final Class clazz, final Class annotationType, final Set> interfaces) { + static List findClassAnnotationInSuperClassesAndIfcs(final Class clazz, + final Class annotationType, final Set> interfaces) { List 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 */ diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java index 11d421c3b4..ff607d32e5 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java @@ -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> jmxInterfaces) { - List descriptions = AnnotationsHelper - .findMethodAnnotationInSuperClassesAndIfcs(setter, Description.class, jmxInterfaces); + List 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> inspectedInterfaces) { + final Set> inspectedInterfaces) { - // only allow setX(ObjectName y) or setX(ObjectName[] y) or setX(List y) to continue + // only allow setX(ObjectName y) or setX(ObjectName[] y) or + // setX(List 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); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java index 1a43d6f884..f768731e51 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java @@ -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) { diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java index 90cc62358a..1ac299bcbb 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java @@ -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; } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java index 63be03f8ad..e07d0d76e1 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java @@ -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> 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 factories = new ArrayList<>(this.moduleNamesToConfigBeanFactories.size()); - Collection> entryCollection = this.moduleNamesToConfigBeanFactories.values(); + Collection> entryCollection = this.moduleNamesToConfigBeanFactories + .values(); for (Map.Entry 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 getModuleFactories() { return moduleFactories; } - } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java index 7d0bee2533..f4b326ea19 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java @@ -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); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java index 1492d5de91..a4fcdbbf8e 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java @@ -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 { diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java index 1f29a65604..e84d2ee953 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java @@ -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. emptyMap()); + defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(moduleIdentifier.getFactoryName(), + moduleIdentifier.getInstanceName(), Collections.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. emptyMap()); + return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier, internalJMXRegistrator, + Collections.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); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java index 9388b8e567..88646b4cc1 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java @@ -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 + + '\'' + '}'; } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java index e9db0715e5..5dc3fe2eca 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java @@ -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; } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java index ff504dafdc..9031f23462 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java @@ -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 serviceNamesToAnnotations) { + final BundleContext bundleContext, + final Map serviceNamesToAnnotations) { return new OsgiRegistration(instance, moduleIdentifier, bundleContext, serviceNamesToAnnotations); } @@ -49,34 +55,36 @@ public class BeanToOsgiServiceManager { @GuardedBy("this") private final Set> serviceRegistrations; @GuardedBy("this") - private final Map serviceNamesToAnnotations; + private final Map serviceNamesToAnnotations; public OsgiRegistration(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier, - final BundleContext bundleContext, - final Map serviceNamesToAnnotations) { + final BundleContext bundleContext, + final Map serviceNamesToAnnotations) { this.instance = instance; this.moduleIdentifier = moduleIdentifier; this.serviceNamesToAnnotations = serviceNamesToAnnotations; this.serviceRegistrations = registerToSR(instance, bundleContext, serviceNamesToAnnotations); } - private static Set> registerToSR(final AutoCloseable instance, final BundleContext bundleContext, - final Map serviceNamesToAnnotations) { + private static Set> registerToSR(final AutoCloseable instance, + final BundleContext bundleContext, + final Map serviceNamesToAnnotations) { Set> serviceRegistrations = new HashSet<>(); - for (Entry entry : serviceNamesToAnnotations.entrySet()) { + for (Entry 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 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 newAnnotationMapping, - final BundleContext bundleContext, final AutoCloseable newInstance) { + public synchronized void updateRegistrations( + final Map 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(); diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java index 8ec44a14ba..2649b145d0 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java @@ -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 { 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 moduleFactoryServiceReference, final Object o) { + public void modifiedService(final ServiceReference moduleFactoryServiceReference, + final Object object) { blankTransactionAsync(); } @Override - public void removedService(final ServiceReference moduleFactoryServiceReference, final Object o) { + public void removedService(final ServiceReference moduleFactoryServiceReference, + final Object object) { blankTransactionAsync(); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java index 1926c6b9af..28f512d848 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java @@ -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 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; } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java index eba7ad1a05..d1c3d767bf 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java @@ -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>> 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 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(); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java index 5841acfde8..132005ac7c 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java @@ -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 + *

+ * Primary customizer may return tracking object, which will be passed to it + * during invocation of * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} * + *

+ * 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. - * + *

+ * 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. + *

+ * Method + * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} is + * never invoked on registered trackers. * - * @param + * @param value */ public final class ExtensibleBundleTracker extends BundleTracker> { 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 primaryTracker; private final BundleTrackerCustomizer[] additionalTrackers; private static final Logger LOG = LoggerFactory.getLogger(ExtensibleBundleTracker.class); - public ExtensibleBundleTracker(final BundleContext context, final BundleTrackerCustomizer primaryBundleTrackerCustomizer, + public ExtensibleBundleTracker(final BundleContext context, + final BundleTrackerCustomizer primaryBundleTrackerCustomizer, final BundleTrackerCustomizer... additionalBundleTrackerCustomizers) { this(context, Bundle.ACTIVE, primaryBundleTrackerCustomizer, additionalBundleTrackerCustomizers); } @@ -72,41 +75,35 @@ public final class ExtensibleBundleTracker extends BundleTracker> { @Override public Future 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 object) { // Intentionally NOOP - } @Override public void removedBundle(final Bundle bundle, final BundleEvent event, final Future 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 extends BundleTracker> { private interface BundleStrategy { void execute(BundleTrackerCustomizer tracker); } - } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java index 5e706250af..e89d6c87aa 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java @@ -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 { private final BlankTransactionServiceTracker blankTransactionServiceTracker; @@ -40,8 +40,7 @@ public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer 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; } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java index 472510f1bb..6cf831510b 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java @@ -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()); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java index 169d1e6ec8..71fcd58400 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java @@ -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>> { +public final class ModuleInfoBundleTracker + implements AutoCloseable, BundleTrackerCustomizer>> { private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class); @@ -72,6 +73,7 @@ public final class ModuleInfoBundleTracker implements AutoCloseable, } @Override + @SuppressWarnings("IllegalCatch") public Collection> 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> 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); } } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java index fcde347881..9871a04f42 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java @@ -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 sourceProvider; @@ -38,39 +35,35 @@ public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, Auto private volatile ServiceRegistration osgiReg; public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry, - final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat, - final SchemaSourceProvider sourceProvider, final BindingContextProvider bindingContextProvider, - final BundleContext bundleContext) { + final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat, + final SchemaSourceProvider 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()); + this.osgiReg = bundleContext.registerService(SchemaContextProvider.class, schemaContextProvider, + new Hashtable()); } public synchronized void updateService() { if (this.osgiReg != null) { - try { - this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider); - - final Dictionary 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 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 registerModuleInfo(final YangModuleInfo yangModuleInfo) { - final ObjectRegistration yangModuleInfoObjectRegistration = this.moduleInfoRegistry.registerModuleInfo(yangModuleInfo); + final ObjectRegistration yangModuleInfoObjectRegistration = this.moduleInfoRegistry + .registerModuleInfo(yangModuleInfo); return new ObjectRegistrationWrapper(yangModuleInfoObjectRegistration); } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java index 8538e3f84d..059ba45ec9 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java @@ -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> 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> toBeInspected = new HashSet<>(); @@ -48,7 +47,7 @@ public final class InterfacesHelper { Iterator> 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> getMXInterfaces( - final Class configBeanClass) { + public static Set> getMXInterfaces(final Class configBeanClass) { Set> allInterfaces = getAllInterfaces(configBeanClass); Set> 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> getServiceInterfaces( - final Class configBeanClass) { + public static Set> getServiceInterfaces(final Class configBeanClass) { Set> allInterfaces = getAllInterfaces(configBeanClass); Set> 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> getAllAbstractServiceClasses(final Class configBeanClass) { + public static Set> getAllAbstractServiceClasses( + final Class configBeanClass) { Set> 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) 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> getOsgiRegistrationTypes( - final Class configBeanClass) { + public static Set> getOsgiRegistrationTypes(final Class configBeanClass) { Set> serviceInterfaces = getServiceInterfaces(configBeanClass); Set> 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 getQNames(final Set siAnnotations) { - Set qNames = new HashSet<>(); - for (ServiceInterfaceAnnotation sia: siAnnotations) { - qNames.add(sia.value()); + Set names = new HashSet<>(); + for (ServiceInterfaceAnnotation sia : siAnnotations) { + names.add(sia.value()); } - return ImmutableSet.copyOf(qNames); + return ImmutableSet.copyOf(names); } public static Set getServiceInterfaceAnnotations(final ModuleFactory factory) { - Set> implementedServiceIntefaces = Collections.unmodifiableSet(factory.getImplementedServiceIntefaces()); + Set> implementedServiceIntefaces = Collections + .unmodifiableSet(factory.getImplementedServiceIntefaces()); return getServiceInterfaceAnnotations(implementedServiceIntefaces); } - private static Set getServiceInterfaceAnnotations(final Set> implementedServiceIntefaces) { - Set> inspected = getAllAbstractServiceInterfaceClasses(implementedServiceIntefaces); + private static Set getServiceInterfaceAnnotations( + final Set> implementedServiceIntefaces) { + Set> inspected = getAllAbstractServiceInterfaceClasses( + implementedServiceIntefaces); Set 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> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs); Set> 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) ifc); } - } return result; } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java index 1fa97acd2f..e1c73df413 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -16,7 +16,7 @@ import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName; import org.opendaylight.yangtools.yang.common.QName; import org.osgi.framework.BundleContext; -public class ModuleQNameUtil { +public final class ModuleQNameUtil { private ModuleQNameUtil() { } @@ -29,7 +29,7 @@ public class ModuleQNameUtil { throw new IllegalArgumentException("Unexpected interface " + inspected); } ModuleQName annotation = null; - while(annotation == null && inspected != null) { + while (annotation == null && inspected != null) { annotation = inspected.getAnnotation(ModuleQName.class); inspected = inspected.getSuperclass(); } @@ -39,5 +39,4 @@ public class ModuleQNameUtil { } return result; } - } diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java index 607cf49db9..2642e56022 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -9,6 +9,7 @@ package org.opendaylight.controller.config.manager.impl.util; import static com.google.common.base.Preconditions.checkNotNull; + import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -26,7 +27,8 @@ public class OsgiRegistrationUtil { } @SafeVarargs - public static AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class ... interfaces) { + public static AutoCloseable registerService(final BundleContext bundleContext, final T service, + final Class... interfaces) { checkNotNull(service); checkNotNull(interfaces); List autoCloseableList = new ArrayList<>(); @@ -52,9 +54,7 @@ public class OsgiRegistrationUtil { return serviceTracker::close; } - /** - * Close list of auto closeables in reverse order - */ + @SuppressWarnings("IllegalCatch") public static AutoCloseable aggregate(final List list) { checkNotNull(list); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java index 5fc5884531..55e8bb2a66 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -24,31 +24,26 @@ import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class ConfigRegistryImplTest extends - AbstractLockedPlatformMBeanServerTest { - private static final Logger LOG = LoggerFactory - .getLogger(ConfigRegistryImplTest.class); +public class ConfigRegistryImplTest extends AbstractLockedPlatformMBeanServerTest { + private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImplTest.class); @Test + @SuppressWarnings("IllegalCatch") public void testFailOnTwoFactoriesExportingSameImpl() { ModuleFactory factory = new TestingFixedThreadPoolModuleFactory(); BundleContext context = mock(BundleContext.class); ConfigRegistryImpl configRegistry = null; try { - ModuleFactoriesResolver resolver = new HardcodedModuleFactoriesResolver(mock(BundleContext.class), - factory, factory); + ModuleFactoriesResolver resolver = new HardcodedModuleFactoriesResolver(mock(BundleContext.class), factory, + factory); - configRegistry = new ConfigRegistryImpl(resolver, - ManagementFactory.getPlatformMBeanServer(), null); + configRegistry = new ConfigRegistryImpl(resolver, ManagementFactory.getPlatformMBeanServer(), null); configRegistry.beginConfig(); fail(); } catch (final IllegalArgumentException e) { - assertTrue( - e.getMessage(), - e.getMessage() - .startsWith("Module name is not unique. Found two conflicting factories with same name " + - "'fixed':")); + assertTrue(e.getMessage(), e.getMessage().startsWith( + "Module name is not unique. Found two conflicting factories with same name " + "'fixed':")); verifyZeroInteractions(context); } finally { try { @@ -59,5 +54,4 @@ public class ConfigRegistryImplTest extends } } } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java index deb202cf00..c03c226978 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -57,7 +57,8 @@ import org.osgi.framework.ServiceRegistration; * needs to subclass this test. * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is * registered to platform MBean Server using - * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)} + * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller + * .config.manager.impl.factoriesresolver.ModuleFactoriesResolver)} * typically during setting up the each test. */ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServerTest { @@ -78,10 +79,13 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ } // Default handler for OSGi service registration - protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler { + protected static class RecordingBundleContextServiceRegistrationHandler + implements BundleContextServiceRegistrationHandler { private final List registrations = new LinkedList<>(); + @Override - public void handleServiceRegistration(final Class clazz, final Object serviceInstance, final Dictionary props) { + public void handleServiceRegistration(final Class clazz, final Object serviceInstance, + final Dictionary props) { this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props)); } @@ -102,7 +106,8 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ } } - protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(final Class serviceType) { + protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler( + final Class serviceType) { return this.currentBundleContextServiceRegistrationHandler; } @@ -116,17 +121,19 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer); - this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator, new BindingContextProvider() { - @Override - public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) { - // NOOP - } + this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator, + new BindingContextProvider() { + @Override + public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, + final SchemaContextProvider ctxProvider) { + // NOOP + } - @Override - public synchronized BindingRuntimeContext getBindingContext() { - return getBindingRuntimeContext(); - } - }); + @Override + public synchronized BindingRuntimeContext getBindingContext() { + return getBindingRuntimeContext(); + } + }); this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer); try { @@ -142,8 +149,10 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ private void initBundleContext() { doNothing().when(this.mockedServiceRegistration).unregister(); final RegisterServiceAnswer answer = new RegisterServiceAnswer(); - doAnswer(answer).when(this.mockedContext).registerService(Matchers.any(), any(), Matchers.>any()); - doAnswer(answer).when(this.mockedContext).registerService(Matchers.>any(), any(), Matchers.>any()); + doAnswer(answer).when(this.mockedContext).registerService(Matchers.any(), any(), + Matchers.>any()); + doAnswer(answer).when(this.mockedContext).registerService(Matchers.>any(), any(), + Matchers.>any()); } @After @@ -156,12 +165,11 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ } /** - * Can be called in @After of tests if some other cleanup is needed that - * would be discarded by closing config beans in this method + * Can be called in @After of tests if some other cleanup is needed that would + * be discarded by closing config beans in this method. */ protected void destroyAllConfigBeans() throws Exception { - final ConfigTransactionJMXClient transaction = this.configRegistryClient - .createTransaction(); + final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction(); Set all = transaction.lookupConfigBeans(); // workaround for getting same Module more times while (all.size() > 0) { @@ -175,23 +183,23 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ final int expectedRecreatedInstances, final int expectedReusedInstances) { assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size()); assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, - status.getRecreatedInstances().size()); + status.getRecreatedInstances().size()); assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, - status.getReusedInstances().size()); + status.getReusedInstances().size()); } - - protected void assertBeanCount(final int i, final String configMXBeanName) { - assertEquals(i, this.configRegistry.lookupConfigBeans(configMXBeanName).size()); + protected void assertBeanCount(final int index, final String configMXBeanName) { + assertEquals(index, this.configRegistry.lookupConfigBeans(configMXBeanName).size()); } /** + * Empty constructor. * * @param configBeanClass - * Empty constructor class of config bean to be instantiated - * whenever create - * @param implementationName - * @return + * Empty constructor class of config bean to be instantiated whenever + * create + * @param implementationName name + * @return factory */ protected ClassBasedModuleFactory createClassBasedCBF(final Class configBeanClass, final String implementationName) { @@ -216,8 +224,7 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ final Object serviceTypeRaw = args[0]; final Object serviceInstance = args[1]; @SuppressWarnings("unchecked") - final - Dictionary props = (Dictionary) args[2]; + final Dictionary props = (Dictionary) args[2]; if (serviceTypeRaw instanceof Class) { final Class serviceType = (Class) serviceTypeRaw; @@ -229,23 +236,27 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ } else if (serviceTypeRaw instanceof String) { invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props); } else { - throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw); + throw new IllegalStateException( + "Not handling service registration of type, Unknown type" + serviceTypeRaw); } return AbstractConfigTest.this.mockedServiceRegistration; } - public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary props) { + public void invokeServiceHandler(final Object serviceInstance, final String className, + final Dictionary props) { try { final Class serviceType = Class.forName(className); invokeServiceHandler(serviceInstance, serviceType, props); } catch (final ClassNotFoundException e) { - throw new IllegalStateException("Not handling service registration of type " + className, e); + throw new IllegalStateException("Not handling service registration of type " + className, e); } } - private void invokeServiceHandler(final Object serviceInstance, final Class serviceType, final Dictionary props) { - final BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType); + private void invokeServiceHandler(final Object serviceInstance, final Class serviceType, + final Dictionary props) { + final BundleContextServiceRegistrationHandler serviceRegistrationHandler = + getBundleContextServiceRegistrationHandler(serviceType); if (serviceRegistrationHandler != null) { serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props); @@ -254,32 +265,34 @@ public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServ } /** - * Expand inner exception wrapped by JMX + * Expand inner exception wrapped by JMX. * - * @param innerObject jmx proxy which will be wrapped and returned + * @param innerObject + * jmx proxy which will be wrapped and returned */ protected T rethrowCause(final T innerObject) { @SuppressWarnings("unchecked") - final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(), + final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(), innerObject.getClass().getInterfaces(), (proxy1, method, args) -> { + try { + return method.invoke(innerObject, args); + } catch (final InvocationTargetException e) { try { - return method.invoke(innerObject, args); - } catch (final InvocationTargetException e) { - try { - throw e.getTargetException(); - } catch (final RuntimeMBeanException e2) { - throw e2.getTargetException(); - } + throw e.getTargetException(); + } catch (final RuntimeMBeanException e2) { + throw e2.getTargetException(); } } - ); + }); return proxy; } /** - * removes contents of the directory - * @param dir to be cleaned - * @throws IOException + * removes contents of the directory. + * + * @param dir + * to be cleaned + * @throws IOException IO exception */ protected void cleanDirectory(final File dir) throws IOException { if (!dir.isDirectory()) { diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java index fbb3d555cc..ced512203e 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -17,26 +17,23 @@ import org.junit.Before; * Each test that works with platform MBeanServer should extend this class. */ public abstract class AbstractLockedPlatformMBeanServerTest { - private static final ReentrantLock lock = new ReentrantLock(); + private static final ReentrantLock LOCK = new ReentrantLock(); protected static MBeanServer platformMBeanServer = ManagementFactory .getPlatformMBeanServer(); @Before public void acquireLock() { - lock.lock(); + LOCK.lock(); } @After public void unlock() { - lock.unlock(); + LOCK.unlock(); } public static class SimpleBean implements SimpleBeanMBean { - } public interface SimpleBeanMBean { - } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java index 7681b00d90..1acf6b2fee 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -18,23 +18,24 @@ public abstract class AbstractMockedModule implements Module { protected abstract AutoCloseable prepareMockedInstance() throws Exception; + @SuppressWarnings("IllegalCatch") public AbstractMockedModule(final DynamicMBeanWithInstance old, final ModuleIdentifier id) { - if(old!=null) + if (old != null) { instance = old.getInstance(); - else + } else { try { instance = prepareMockedInstance(); } catch (final Exception e) { throw new RuntimeException(e); } + } - this.id = id==null ? new ModuleIdentifier(getClass().getCanonicalName(), "mock") : id; + this.id = id == null ? new ModuleIdentifier(getClass().getCanonicalName(), "mock") : id; } - @Override public boolean canReuse(final Module oldModule) { - return instance!=null; + return instance != null; } @Override @@ -50,5 +51,4 @@ public abstract class AbstractMockedModule implements Module { public ModuleIdentifier getIdentifier() { return id; } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java index 451d85f780..93661699c4 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -26,9 +26,9 @@ import org.osgi.framework.BundleContext; /** * Creates new modules by reflection. Provided class must have this constructor: - * ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class). - * When reconfiguring, both parameters will be non null. When creating new - * instance first parameter will be null. + * ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class). When + * reconfiguring, both parameters will be non null. When creating new instance + * first parameter will be null. * */ public class ClassBasedModuleFactory implements ModuleFactory { @@ -36,14 +36,15 @@ public class ClassBasedModuleFactory implements ModuleFactory { private final Class configBeanClass; /** + * Module factory constructor. + * * @param implementationName + * name of the implementation * @param configBeanClass - * class that will be instantiated when createModule is called. - * This class must implement Module interface and all exported - * interfaces. + * class that will be instantiated when createModule is called. This + * class must implement Module interface and all exported interfaces. */ - public ClassBasedModuleFactory(final String implementationName, - final Class configBeanClass) { + public ClassBasedModuleFactory(final String implementationName, final Class configBeanClass) { this.implementationName = implementationName; this.configBeanClass = configBeanClass; } @@ -54,38 +55,39 @@ public class ClassBasedModuleFactory implements ModuleFactory { } @Override - public Module createModule(final String instanceName, - final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) - throws Exception { + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { Preconditions.checkNotNull(old); return constructModule(instanceName, dependencyResolver, old); } - private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old) throws InstantiationException, IllegalAccessException, InvocationTargetException { + @Override + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final BundleContext bundleContext) { + try { + return constructModule(instanceName, dependencyResolver, null); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver, + final DynamicMBeanWithInstance old) + throws InstantiationException, IllegalAccessException, InvocationTargetException { Preconditions.checkNotNull(dependencyResolver); ModuleIdentifier moduleIdentifier = new ModuleIdentifier(implementationName, instanceName); Constructor declaredConstructor; try { - declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class, ModuleIdentifier.class); + declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class, + ModuleIdentifier.class); } catch (final NoSuchMethodException e) { throw new IllegalStateException( - "Did not find constructor with parameters (DynamicMBeanWithInstance) in " - + configBeanClass, e); + "Did not find constructor with parameters (DynamicMBeanWithInstance) in " + configBeanClass, e); } Preconditions.checkState(declaredConstructor != null); return declaredConstructor.newInstance(old, moduleIdentifier); } - @Override - public Module createModule(final String instanceName, - final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - try { - return constructModule(instanceName, dependencyResolver, null); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - @Override public boolean isModuleImplementingServiceInterface( final Class serviceInterface) { @@ -104,7 +106,8 @@ public class ClassBasedModuleFactory implements ModuleFactory { } @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext bundleContext) { return new HashSet<>(); } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java index eabf8ec520..8368a2723f 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -29,75 +29,65 @@ import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator; import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl; import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean; -public class ConfigRegistryImplLookupTest extends - AbstractLockedPlatformMBeanServerTest { +public class ConfigRegistryImplLookupTest extends AbstractLockedPlatformMBeanServerTest { private ConfigRegistryImpl configRegistryImpl; private BaseJMXRegistrator baseJMXRegistrator; - private static final String moduleNameA = "moduleA"; - private static final String moduleNameB = "moduleB"; + private static final String MODULE_NAMEA = "moduleA"; + private static final String MODULE_NAMEB = "moduleB"; - private static final String instanceNameA = "instA"; - private static final String instanceNameB = "instB"; - private static final String instanceNameC = "instC"; + private static final String INSTANCE_NAMEA = "instA"; + private static final String INSTANCE_NAMEB = "instB"; + private static final String INSTANCE_NAMEC = "instC"; - private static final ObjectName name1 = ObjectNameUtil - .createReadOnlyModuleON(moduleNameA, instanceNameA); - private static final ObjectName name2 = ObjectNameUtil - .createReadOnlyModuleON(moduleNameA, instanceNameB); - private static final ObjectName name3 = ObjectNameUtil - .createReadOnlyModuleON(moduleNameA, instanceNameC); - private static final ObjectName name4 = ObjectNameUtil - .createReadOnlyModuleON(moduleNameB, instanceNameA); + private static final ObjectName NAME1 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEA); + private static final ObjectName NAME2 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEB); + private static final ObjectName NAME3 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEC); + private static final ObjectName NAME4 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEB, INSTANCE_NAMEA); - private static final ObjectName name5 = ObjectNameUtil - .createRuntimeBeanName(moduleNameA, instanceNameA, Collections.emptyMap()); - private static final ObjectName name6 = ObjectNameUtil - .createRuntimeBeanName(moduleNameA, instanceNameB, Collections.emptyMap()); - private static final ObjectName name8 = ObjectNameUtil - .createRuntimeBeanName(moduleNameB, instanceNameA, Collections.emptyMap()); + private static final ObjectName NAME5 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEA, + Collections.emptyMap()); + private static final ObjectName NAME6 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEB, + Collections.emptyMap()); + private static final ObjectName NAME8 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEB, INSTANCE_NAMEA, + Collections.emptyMap()); - private static final ObjectName name9 = ObjectNameUtil - .createTransactionModuleON("transaction", moduleNameA, instanceNameA); + private static final ObjectName NAME9 = ObjectNameUtil.createTransactionModuleON("transaction", MODULE_NAMEA, + INSTANCE_NAMEA); @Before public void setUp() throws Exception { - configRegistryImpl = new ConfigRegistryImpl(null, - ManagementFactory.getPlatformMBeanServer(), null); - Field field = configRegistryImpl.getClass().getDeclaredField( - "baseJMXRegistrator"); + configRegistryImpl = new ConfigRegistryImpl(null, ManagementFactory.getPlatformMBeanServer(), null); + Field field = configRegistryImpl.getClass().getDeclaredField("baseJMXRegistrator"); field.setAccessible(true); baseJMXRegistrator = (BaseJMXRegistrator) field.get(configRegistryImpl); - registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name1); - registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name2); - registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name3); - registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name4); + registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME1); + registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME2); + registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME3); + registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME4); - registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name5); - registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name6); - registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name8); + registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME5); + registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME6); + registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME8); - baseJMXRegistrator.createTransactionJMXRegistrator("transaction") - .createTransactionModuleJMXRegistrator() - .registerMBean(new TestingRuntimeBean(), name9); + baseJMXRegistrator.createTransactionJMXRegistrator("transaction").createTransactionModuleJMXRegistrator() + .registerMBean(new TestingRuntimeBean(), NAME9); } private static void registerModuleBean(final TestingRuntimeBean testingRuntimeBean, final BaseJMXRegistrator baseJMXRegistrator, final ObjectName objectName) throws InstanceAlreadyExistsException { - baseJMXRegistrator.createModuleJMXRegistrator().registerMBean( - testingRuntimeBean, objectName); + baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(testingRuntimeBean, objectName); } private static void registerRuntimeBean(final RuntimeBean object, final BaseJMXRegistrator baseJMXRegistrator, final ObjectName runtimeON) throws InstanceAlreadyExistsException { String factoryName = ObjectNameUtil.getFactoryName(runtimeON); String instanceName = ObjectNameUtil.getInstanceName(runtimeON); - Map properties = ObjectNameUtil - .getAdditionalPropertiesOfRuntimeBeanName(runtimeON); + Map properties = ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(runtimeON); RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator .createRuntimeBeanRegistrator(new ModuleIdentifier(factoryName, instanceName)); @@ -115,39 +105,34 @@ public class ConfigRegistryImplLookupTest extends @Test public void testLookupConfigBeans() throws Exception { Set beans = configRegistryImpl.lookupConfigBeans(); - assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans); + assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans); beans = configRegistryImpl.lookupConfigBeans(); - assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans); + assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans); } @Test public void testLookupConfigBeanWithModuleName() throws Exception { - Set bean = configRegistryImpl - .lookupConfigBeans(moduleNameA); - assertEquals(Sets.newHashSet(name1, name2, name3), bean); + Set bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA); + assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), bean); } @Test - public void testLookupConfigBeanWithModuleNameAndInstanceName() - throws Exception { - Set bean = configRegistryImpl.lookupConfigBeans( - moduleNameA, instanceNameA); - assertEquals(Sets.newHashSet(name1), bean); + public void testLookupConfigBeanWithModuleNameAndInstanceName() throws Exception { + Set bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA, INSTANCE_NAMEA); + assertEquals(Sets.newHashSet(NAME1), bean); } @Test public void testLookupRuntimeBeans() throws Exception { Set beans = configRegistryImpl.lookupRuntimeBeans(); - assertEquals(Sets.newHashSet(name5, name6, name8), beans); + assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans); beans = configRegistryImpl.lookupRuntimeBeans(null, null); - assertEquals(Sets.newHashSet(name5, name6, name8), beans); + assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans); } @Test public void testLookupRuntimeBeansWithIFcNameAndImplName() throws Exception { - Set beans = configRegistryImpl.lookupRuntimeBeans( - moduleNameA, instanceNameA); - assertEquals(Sets.newHashSet(name5), beans); + Set beans = configRegistryImpl.lookupRuntimeBeans(MODULE_NAMEA, INSTANCE_NAMEA); + assertEquals(Sets.newHashSet(NAME5), beans); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java index 9263e42948..82666e8e6a 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -28,63 +28,58 @@ import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRunti import org.opendaylight.controller.config.spi.ModuleFactory; import org.osgi.framework.BundleContext; -public class ConfigTransactionControllerImplTest extends - AbstractLockedPlatformMBeanServerTest { +public class ConfigTransactionControllerImplTest extends AbstractLockedPlatformMBeanServerTest { private BaseJMXRegistrator baseJMXRegistrator; private ConfigTransactionControllerImpl testedTxController; private MBeanServer transactionsMBeanServer; - private static final String transactionName123 = "testTX1"; - private static final String transactionName4 = "testTX2"; + private static final String TRANSACTION_NAME123 = "testTX1"; + private static final String TRANSACTION_NAME4 = "testTX2"; - private static final String moduleName124 = "module124"; - private static final String moduleName3 = "module3"; + private static final String MODULE_NAME124 = "module124"; + private static final String MODULE_NAME3 = "module3"; - private static final String instanceName134 = "instA"; - private static final String instanceName2 = "instB"; + private static final String INSTANCE_NAME134 = "instA"; + private static final String INSTANCE_NAME2 = "instB"; - private static final ObjectName name1 = ObjectNameUtil - .createTransactionModuleON(transactionName123, moduleName124, instanceName134); - private static final ObjectName name2 = ObjectNameUtil - .createTransactionModuleON(transactionName123, moduleName124, instanceName2); - private static final ObjectName name3 = ObjectNameUtil - .createTransactionModuleON(transactionName123, moduleName3, instanceName134); - private static final ObjectName name4 = ObjectNameUtil - .createTransactionModuleON(transactionName4, moduleName124, instanceName134); + private static final ObjectName NAME1 = + ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME124, INSTANCE_NAME134); + private static final ObjectName NAME2 = + ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, + MODULE_NAME124, INSTANCE_NAME2); + private static final ObjectName NAME3 = + ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME3, INSTANCE_NAME134); + private static final ObjectName NAME4 = + ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME4, MODULE_NAME124, INSTANCE_NAME134); @Before public void setUp() throws Exception { - baseJMXRegistrator = new BaseJMXRegistrator( - ManagementFactory.getPlatformMBeanServer()); + baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer()); transactionsMBeanServer = MBeanServerFactory.createMBeanServer(); Map> currentlyRegisteredFactories = new HashMap<>(); ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry( - new TransactionIdentifier(transactionName123), () -> - baseJMXRegistrator.createTransactionJMXRegistrator(transactionName123), currentlyRegisteredFactories); + new TransactionIdentifier(TRANSACTION_NAME123), + () -> baseJMXRegistrator.createTransactionJMXRegistrator(TRANSACTION_NAME123), + currentlyRegisteredFactories); - SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry( - ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(), txLookupRegistry, currentlyRegisteredFactories); + SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl + .createSRWritableRegistry(ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(), + txLookupRegistry, currentlyRegisteredFactories); - - testedTxController = new ConfigTransactionControllerImpl( - txLookupRegistry, 1, null, 1, - currentlyRegisteredFactories, transactionsMBeanServer, - ManagementFactory.getPlatformMBeanServer(), false, writableRegistry); + testedTxController = new ConfigTransactionControllerImpl(txLookupRegistry, 1, null, 1, + currentlyRegisteredFactories, transactionsMBeanServer, ManagementFactory.getPlatformMBeanServer(), + false, writableRegistry); TransactionModuleJMXRegistrator transactionModuleJMXRegistrator123 = testedTxController .getTxModuleJMXRegistrator(); - transactionModuleJMXRegistrator123.registerMBean( - new TestingRuntimeBean(), name1); - transactionModuleJMXRegistrator123.registerMBean( - new TestingRuntimeBean(), name2); - transactionModuleJMXRegistrator123.registerMBean( - new TestingRuntimeBean(), name3); + transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME1); + transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME2); + transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME3); TransactionJMXRegistrator jmxRegistrator4 = baseJMXRegistrator - .createTransactionJMXRegistrator(transactionName4); - jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean( - new TestingRuntimeBean(), name4); + .createTransactionJMXRegistrator(TRANSACTION_NAME4); + jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(new TestingRuntimeBean(), NAME4); } @After @@ -94,25 +89,23 @@ public class ConfigTransactionControllerImplTest extends } /** - * Tests if lookup method returns all beans with defined transaction name + * Tests if lookup method returns all beans with defined transaction name. */ @Test public void testLookupConfigBeans() { Set beans = testedTxController.lookupConfigBeans(); - assertEquals(Sets.newHashSet(name1, name2, name3), beans); + assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), beans); } @Test public void testLookupConfigBeansWithModuleName() { - Set beans = testedTxController - .lookupConfigBeans(moduleName124); - assertEquals(Sets.newHashSet(name1, name2), beans); + Set beans = testedTxController.lookupConfigBeans(MODULE_NAME124); + assertEquals(Sets.newHashSet(NAME1, NAME2), beans); } @Test public void lookupConfigBeansWithModuleNameAndImplName() throws Exception { - Set beans = testedTxController.lookupConfigBeans( - moduleName124, instanceName134); - assertEquals(Sets.newHashSet(name1), beans); + Set beans = testedTxController.lookupConfigBeans(MODULE_NAME124, INSTANCE_NAME134); + assertEquals(Sets.newHashSet(NAME1), beans); } -} \ No newline at end of file +} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java index cc4d3cad36..ede2a805a8 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -32,7 +32,7 @@ public class ConfigTransactionManagerImplTest extends try { configRegistryJMXRegistrator.registerToJMX(mockedRegistry); fail(); - } catch (final Exception e) { + } catch (final InstanceAlreadyExistsException e) { assertTrue(e instanceof InstanceAlreadyExistsException); } } @@ -49,5 +49,4 @@ public class ConfigTransactionManagerImplTest extends .createTransaction(); transaction.commit(); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java index 9b9a92270a..5ab1557023 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -38,14 +38,11 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest { - @Before public void setUp() { - super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver( - mockedContext, - new TestingFixedThreadPoolModuleFactory(), - new TestingParallelAPSPModuleFactory(), - new TestingScheduledThreadPoolModuleFactory())); + super.initConfigTransactionManagerImpl( + new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory(), + new TestingParallelAPSPModuleFactory(), new TestingScheduledThreadPoolModuleFactory())); } @Override @@ -57,19 +54,19 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest { public void test() throws Exception { ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction(); // create fixed1 - int fixedNrOfThreads = 20, scheduledNrOfThreads = 30; + int fixedNrOfThreads = 20; + int scheduledNrOfThreads = 30; ObjectName fixedTPTransactionON = transaction1.createModule(getThreadPoolImplementationName(), fixed1); platformMBeanServer.setAttribute(fixedTPTransactionON, new Attribute("ThreadCount", fixedNrOfThreads)); - ObjectName scheduledTPTransactionON = transaction1.createModule( - TestingScheduledThreadPoolModuleFactory.NAME, "scheduled1"); - platformMBeanServer.setAttribute(scheduledTPTransactionON, new Attribute("ThreadCount", - scheduledNrOfThreads)); + ObjectName scheduledTPTransactionON = transaction1.createModule(TestingScheduledThreadPoolModuleFactory.NAME, + "scheduled1"); + platformMBeanServer.setAttribute(scheduledTPTransactionON, new Attribute("ThreadCount", scheduledNrOfThreads)); String refName = "ref"; - ObjectName serviceReference = transaction1.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName, - fixedTPTransactionON); + ObjectName serviceReference = transaction1.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, + refName, fixedTPTransactionON); // create apsp-parallel createParallelAPSP(transaction1, serviceReference); transaction1.commit(); @@ -81,11 +78,12 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest { checkApspThreadCount(fixedNrOfThreads); // check OSGi SR List registrations = - ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler).getRegistrations(); + ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler) + .getRegistrations(); assertEquals(1, registrations.size()); RegistrationHolder record = registrations.get(0); assertEquals(TestingThreadPoolIfc.class, record.clazz); - assertEquals(ImmutableMap.of("name","ref"), record.props); + assertEquals(ImmutableMap.of("name", "ref"), record.props); // switch reference to scheduled ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction(); @@ -95,21 +93,22 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest { // check scheduled is used checkApspThreadCount(scheduledNrOfThreads); // check that dummy MXBean points to scheduled - assertEquals(withoutTransactionName(scheduledTPTransactionON), serviceReferenceMXBean.getCurrentImplementation()); + assertEquals(withoutTransactionName(scheduledTPTransactionON), + serviceReferenceMXBean.getCurrentImplementation()); // empty transaction configRegistryClient.createTransaction().commit(); // get service mapping - Map> serviceMapping = configRegistryClient.getServiceMapping(); - Map> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME, - (Map)ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON))); + Map> serviceMapping = configRegistryClient.getServiceMapping(); + Map> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME, + (Map) ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON))); assertEquals(expectedMapping, serviceMapping); // destroy all ConfigTransactionJMXClient transaction4 = configRegistryClient.createTransaction(); Set objectNames = transaction4.lookupConfigBeans(); - for(ObjectName on: objectNames) { + for (ObjectName on : objectNames) { transaction4.destroyModule(on); } transaction4.commit(); @@ -118,8 +117,8 @@ public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest { assertTrue(serviceMapping.isEmpty()); } - private void checkApspThreadCount(final int fixedNrOfThreads) throws MBeanException, AttributeNotFoundException, - InstanceNotFoundException, ReflectionException { + private void checkApspThreadCount(final int fixedNrOfThreads) + throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { ObjectName apspON = ObjectNameUtil.createReadOnlyModuleON(TestingParallelAPSPModuleFactory.NAME, apsp1); assertEquals(fixedNrOfThreads, platformMBeanServer.getAttribute(apspON, "MaxNumberOfThreads")); } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java index 20a127ed23..0f099e77b0 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -34,10 +34,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe final ModuleIdentifier apspName = new ModuleIdentifier("apsp", "apsp"); // depends // on: - final ModuleIdentifier threadPoolName = new ModuleIdentifier("threadpool", - "threadpool"); // depends on: - final ModuleIdentifier threadFactoryName = new ModuleIdentifier( - "threadfactory", "threadfactory"); + final ModuleIdentifier threadPoolName = new ModuleIdentifier("threadpool", "threadpool"); // depends on: + final ModuleIdentifier threadFactoryName = new ModuleIdentifier("threadfactory", "threadfactory"); private DependencyResolverManager tested; TransactionStatus transactionStatus; @@ -54,10 +52,9 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe @Test public void testOrdering() { - DependencyResolverImpl apspDRI = tested.getOrCreate(apspName); + final DependencyResolverImpl apspDRI = tested.getOrCreate(apspName); mockGetInstance(tested, apspName); - DependencyResolverImpl threadPoolDRI = tested - .getOrCreate(threadPoolName); + final DependencyResolverImpl threadPoolDRI = tested.getOrCreate(threadPoolName); mockGetInstance(tested, threadPoolName); tested.getOrCreate(threadFactoryName); mockGetInstance(tested, threadFactoryName); @@ -73,12 +70,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe doNothing().when(transactionStatus).checkCommitted(); doNothing().when(transactionStatus).checkNotCommitted(); - List sortedModuleIdentifiers = tested - .getSortedModuleIdentifiers(); - assertEquals( - Arrays.asList(threadFactoryName, threadPoolName, apspName), - sortedModuleIdentifiers); - + List sortedModuleIdentifiers = tested.getSortedModuleIdentifiers(); + assertEquals(Arrays.asList(threadFactoryName, threadPoolName, apspName), sortedModuleIdentifiers); } /** @@ -88,8 +81,7 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe private static void declareDependency(final DependencyResolverImpl dependerResolver, final ModuleIdentifier dependentName) { JmxAttribute dummyAttribute = new JmxAttribute("dummy"); - dependerResolver.resolveInstance(Object.class, - ObjectNameUtil.createReadOnlyModuleON(dependentName), + dependerResolver.resolveInstance(Object.class, ObjectNameUtil.createReadOnlyModuleON(dependentName), dummyAttribute); } @@ -101,12 +93,8 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe TransactionModuleJMXRegistration transactionModuleJMXRegistration = null; boolean isDefaultBean = false; - tested.put(moduleIdentifier, - mockedModule(), - moduleFactory, - maybeOldInternalInfo, - transactionModuleJMXRegistration, - isDefaultBean, mock(BundleContext.class)); + tested.put(moduleIdentifier, mockedModule(), moduleFactory, maybeOldInternalInfo, + transactionModuleJMXRegistration, isDefaultBean, mock(BundleContext.class)); } private static Module mockedModule() { @@ -115,5 +103,4 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe doReturn(new ModuleIdentifier("fact", "instance")).when(mockedModule).getIdentifier(); return mockedModule; } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java index afd088c62f..6f65a1e153 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -30,35 +30,31 @@ import org.opendaylight.controller.config.manager.testingservices.threadpool.Tes import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory; import org.opendaylight.controller.config.spi.Module; -public abstract class AbstractDynamicWrapperTest extends - AbstractLockedPlatformMBeanServerTest { - protected final MBeanServer platformMBeanServer = ManagementFactory - .getPlatformMBeanServer(); - private static final String moduleName = "impl"; - protected final ObjectName threadPoolDynamicWrapperON = ObjectNameUtil - .createReadOnlyModuleON(moduleName, "fixed1"); +public abstract class AbstractDynamicWrapperTest extends AbstractLockedPlatformMBeanServerTest { + protected final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); + private static final String MODULE_NAME = "impl"; + protected final ObjectName threadPoolDynamicWrapperON = + ObjectNameUtil.createReadOnlyModuleON(MODULE_NAME, "fixed1"); protected static final String THREAD_COUNT = "ThreadCount"; protected static final String TRIGGER_NEW_INSTANCE_CREATION = "TriggerNewInstanceCreation"; protected final int threadCount = 5; protected TestingFixedThreadPoolModule threadPoolConfigBean; - private static final ModuleIdentifier moduleIdentifier = new ModuleIdentifier( - moduleName, "clientname2"); + private static final ModuleIdentifier MODULE_IDENTIFIER = + new ModuleIdentifier(MODULE_NAME, "clientname2"); protected MBeanServer internalServer; @Before public void registerToJMX() throws Exception { internalServer = MBeanServerFactory.createMBeanServer(); - TestingFixedThreadPoolModuleFactory testingFixedThreadPoolConfigBeanFactory = new TestingFixedThreadPoolModuleFactory(); - threadPoolConfigBean = testingFixedThreadPoolConfigBeanFactory - .createModule("", null, null); + TestingFixedThreadPoolModuleFactory testingFixedThreadPoolConfigBeanFactory = + new TestingFixedThreadPoolModuleFactory(); + threadPoolConfigBean = testingFixedThreadPoolConfigBeanFactory.createModule("", null, null); threadPoolConfigBean.setThreadCount(threadCount); - AbstractDynamicWrapper dynamicWrapper = getDynamicWrapper( - threadPoolConfigBean, moduleIdentifier); - platformMBeanServer.registerMBean(dynamicWrapper, - threadPoolDynamicWrapperON); + AbstractDynamicWrapper dynamicWrapper = getDynamicWrapper(threadPoolConfigBean, MODULE_IDENTIFIER); + platformMBeanServer.registerMBean(dynamicWrapper, threadPoolDynamicWrapperON); } @After @@ -68,42 +64,34 @@ public abstract class AbstractDynamicWrapperTest extends MBeanServerFactory.releaseMBeanServer(internalServer); } - protected abstract AbstractDynamicWrapper getDynamicWrapper(Module module, - ModuleIdentifier moduleIdentifier); + protected abstract AbstractDynamicWrapper getDynamicWrapper(Module module, ModuleIdentifier moduleIdentifier); @Test public void testReadAttributes() throws Exception { - - DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, - threadPoolDynamicWrapperON, DynamicMBean.class); + DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class); assertEquals(threadCount, proxy.getAttribute(THREAD_COUNT)); assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), proxy.getAttribute(TRIGGER_NEW_INSTANCE_CREATION)); - AttributeList attributes = proxy.getAttributes(new String[] { - THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION }); + AttributeList attributes = proxy.getAttributes(new String[] { THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION }); assertEquals(2, attributes.size()); Attribute threadCountAttr = (Attribute) attributes.get(0); assertEquals(THREAD_COUNT, threadCountAttr.getName()); assertEquals(threadCount, threadCountAttr.getValue()); Attribute boolTestAttr = (Attribute) attributes.get(1); assertEquals(TRIGGER_NEW_INSTANCE_CREATION, boolTestAttr.getName()); - assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), - boolTestAttr.getValue()); - - MBeanInfo mBeanInfo = proxy.getMBeanInfo(); - assertEquals(2, mBeanInfo.getAttributes().length); + assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), boolTestAttr.getValue()); + MBeanInfo beanInfo = proxy.getMBeanInfo(); + assertEquals(2, beanInfo.getAttributes().length); } @Test public void testGettersWithMXBeanProxy() { - TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy( - platformMBeanServer, threadPoolDynamicWrapperON, + TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, TestingFixedThreadPoolConfigMXBean.class); assertEquals(threadCount, proxy.getThreadCount()); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java index 854b40eb24..4efbebbf46 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -36,8 +36,7 @@ public class AnnotationsTest { private static void assertRequireInterfaceAnnotationHasCorrectValue(final Class clazz, final String methodName, final Set> inspectedInterfaces, final Class expectedValue) { Method setter = findMethod(clazz, methodName); - RequireInterface found = AttributeHolder - .findRequireInterfaceAnnotation(setter, inspectedInterfaces); + RequireInterface found = AttributeHolder.findRequireInterfaceAnnotation(setter, inspectedInterfaces); if (expectedValue == null) { assertNull(found); } else { @@ -50,7 +49,7 @@ public class AnnotationsTest { Method setter; try { setter = clazz.getMethod(methodName, new Class[] { ObjectName.class }); - } catch (final Exception e) { + } catch (final NoSuchMethodException e) { throw Throwables.propagate(e); } return setter; @@ -59,8 +58,7 @@ public class AnnotationsTest { private static void assertDescription(final Class clazz, final String methodName, final Set> exportedInterfaces, final String expectedValue) { Method setter = findMethod(clazz, methodName); - String found = AttributeHolder.findDescription(setter, - exportedInterfaces); + String found = AttributeHolder.findDescription(setter, exportedInterfaces); if (expectedValue == null) { assertNull(found); } else { @@ -88,10 +86,10 @@ public class AnnotationsTest { static final String SIMPLE = "simple"; static final String SUBCLASS2 = "subclass2"; - @ServiceInterfaceAnnotation(value = SIMPLE, osgiRegistrationType = Executor.class, - namespace = "ns", revision = "rev", localName = SIMPLE) + @ServiceInterfaceAnnotation(value = SIMPLE, + osgiRegistrationType = Executor.class, + namespace = "ns", revision = "rev", localName = SIMPLE) interface SimpleSI extends AbstractServiceInterface { - } @Description("class") @@ -109,12 +107,10 @@ public class AnnotationsTest { @Test public void testFindAnnotation_directly() throws Exception { - assertRequireInterfaceAnnotationHasCorrectValue(SuperClass.class, - setSomethingString, emptySetOfInterfaces(), SimpleSI.class); - assertDescription(SuperClass.class, setSomethingString, - emptySetOfInterfaces(), "descr"); - assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), - "class"); + assertRequireInterfaceAnnotationHasCorrectValue(SuperClass.class, setSomethingString, emptySetOfInterfaces(), + SimpleSI.class); + assertDescription(SuperClass.class, setSomethingString, emptySetOfInterfaces(), "descr"); + assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class"); } public static class SubClassWithout extends SuperClass { @@ -123,12 +119,10 @@ public class AnnotationsTest { @Test public void testFindAnnotation_subclassWithout() throws Exception { - assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithout.class, - setSomethingString, emptySetOfInterfaces(), SimpleSI.class); - assertDescription(SubClassWithout.class, setSomethingString, - emptySetOfInterfaces(), "descr"); - assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), - "class"); + assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithout.class, setSomethingString, + emptySetOfInterfaces(), SimpleSI.class); + assertDescription(SubClassWithout.class, setSomethingString, emptySetOfInterfaces(), "descr"); + assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class"); } public static class SubClassWithEmptyMethod extends SuperClass { @@ -140,23 +134,19 @@ public class AnnotationsTest { @Test public void testOverridingWithoutAnnotation() throws Exception { - assertRequireInterfaceAnnotationHasCorrectValue( - SubClassWithEmptyMethod.class, setSomethingString, + assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithEmptyMethod.class, setSomethingString, emptySetOfInterfaces(), SimpleSI.class); - assertDescription(SubClassWithEmptyMethod.class, setSomethingString, - emptySetOfInterfaces(), "descr"); - assertDescriptionOnClass(SubClassWithEmptyMethod.class, - emptySetOfInterfaces(), "class"); + assertDescription(SubClassWithEmptyMethod.class, setSomethingString, emptySetOfInterfaces(), "descr"); + assertDescriptionOnClass(SubClassWithEmptyMethod.class, emptySetOfInterfaces(), "class"); } interface SubSI extends SimpleSI { } - @ServiceInterfaceAnnotation(value = SUBCLASS2, osgiRegistrationType = ExecutorService.class, - namespace = "ns", revision = "rev", localName = SUBCLASS2) + @ServiceInterfaceAnnotation(value = SUBCLASS2, + osgiRegistrationType = ExecutorService.class, namespace = "ns", revision = "rev", localName = SUBCLASS2) interface SubSI2 extends SubSI { - } public static class SubClassWithAnnotation extends SuperClass { @@ -173,11 +163,11 @@ public class AnnotationsTest { assertDescription(SubClassWithAnnotation.class, setSomethingString, emptySetOfInterfaces(), "descr2\ndescr"); try { assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithAnnotation.class, setSomethingString, - emptySetOfInterfaces(), SubSI2.class); + emptySetOfInterfaces(), SubSI2.class); fail(); } catch (final IllegalStateException e) { assertTrue(e.getMessage(), - e.getMessage().startsWith("Error finding @RequireInterface. More than one value specified")); + e.getMessage().startsWith("Error finding @RequireInterface. More than one value specified")); } } @@ -190,39 +180,31 @@ public class AnnotationsTest { } @Test - public void testFindAnnotation_SubClassWithoutMethodWithInterface() - throws Exception { - assertRequireInterfaceAnnotationHasCorrectValue( - SubClassWithoutMethodWithInterface.class, setSomethingString, + public void testFindAnnotation_SubClassWithoutMethodWithInterface() throws Exception { + assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithoutMethodWithInterface.class, setSomethingString, emptySetOfInterfaces(), SimpleSI.class); - assertDescription(SubClassWithoutMethodWithInterface.class, - setSomethingString, emptySetOfInterfaces(), "descr"); + assertDescription(SubClassWithoutMethodWithInterface.class, setSomethingString, emptySetOfInterfaces(), + "descr"); } - static abstract class SuperClassWithInterface implements HasSomeMethod { + abstract static class SuperClassWithInterface implements HasSomeMethod { @Override @RequireInterface(SubSI2.class) @Description("descr") public void setSomething(final ObjectName objectName) { - } } @Description("class") public static class SubClassOfSuperClassWithInterface extends SuperClassWithInterface { - } @Test - public void testFindAnnotation_SubClassOfSuperClassWithInterface() - throws Exception { - assertRequireInterfaceAnnotationHasCorrectValue( - SubClassOfSuperClassWithInterface.class, setSomethingString, + public void testFindAnnotation_SubClassOfSuperClassWithInterface() throws Exception { + assertRequireInterfaceAnnotationHasCorrectValue(SubClassOfSuperClassWithInterface.class, setSomethingString, emptySetOfInterfaces(), SubSI2.class); - assertDescription(SubClassOfSuperClassWithInterface.class, - setSomethingString, emptySetOfInterfaces(), "descr"); - assertDescriptionOnClass(SubClassOfSuperClassWithInterface.class, - emptySetOfInterfaces(), "class"); + assertDescription(SubClassOfSuperClassWithInterface.class, setSomethingString, emptySetOfInterfaces(), "descr"); + assertDescriptionOnClass(SubClassOfSuperClassWithInterface.class, emptySetOfInterfaces(), "class"); } @Test @@ -245,8 +227,7 @@ public class AnnotationsTest { @Test public void testHasSomeMethodWithAnnotationsImpl() { - HashSet> exportedInterfaces = Sets - .> newHashSet(HasSomeMethodWithAnnotations.class); + HashSet> exportedInterfaces = Sets.>newHashSet(HasSomeMethodWithAnnotations.class); assertRequireInterfaceAnnotationHasCorrectValue(HasSomeMethodWithAnnotationsImpl.class, setSomethingString, exportedInterfaces, SubSI2.class); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java index 100ed62b82..48accc56ac 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -9,6 +9,7 @@ package org.opendaylight.controller.config.manager.impl.dynamicmbean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; + import java.util.concurrent.atomic.AtomicBoolean; import javax.management.Attribute; import javax.management.AttributeList; @@ -29,22 +30,17 @@ import org.opendaylight.controller.config.spi.Module; public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest { private final int newThreadCount = 10; private final AtomicBoolean atomicBoolean = new AtomicBoolean(); - private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl( - atomicBoolean); + private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(atomicBoolean); @Override - protected AbstractDynamicWrapper getDynamicWrapper(final Module module, - final ModuleIdentifier moduleIdentifier) { - return new DynamicWritableWrapper(module, moduleIdentifier, - "transaction-1", - readOnlyAtomicBoolean, MBeanServerFactory.createMBeanServer(), - platformMBeanServer); + protected AbstractDynamicWrapper getDynamicWrapper(final Module module, final ModuleIdentifier moduleIdentifier) { + return new DynamicWritableWrapper(module, moduleIdentifier, "transaction-1", readOnlyAtomicBoolean, + MBeanServerFactory.createMBeanServer(), platformMBeanServer); } @Test public void testSetAttribute() throws Exception { - DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, - threadPoolDynamicWrapperON, DynamicMBean.class); + DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class); proxy.setAttribute(new Attribute(THREAD_COUNT, newThreadCount)); @@ -63,40 +59,31 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest { @Test public void testSettersWithMXBeanProxy() { - TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy( - platformMBeanServer, threadPoolDynamicWrapperON, + TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, TestingFixedThreadPoolConfigMXBean.class); proxy.setThreadCount(newThreadCount); assertEquals(newThreadCount, threadPoolConfigBean.getThreadCount()); } /* - * Try to call setter with ObjectName containing transaction name. Verify - * that ObjectName without transaction name was actually passed on the - * config bean. + * Try to call setter with ObjectName containing transaction name. Verify that + * ObjectName without transaction name was actually passed on the config bean. */ @Test - public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON() - throws Exception { + public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON() throws Exception { TestingParallelAPSPModuleFactory testingParallelAPSPConfigBeanFactory = new TestingParallelAPSPModuleFactory(); - TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory - .createModule("", null, null); - ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp", - "parallel"); - ObjectName dynON2 = ObjectNameUtil - .createReadOnlyModuleON(moduleIdentifier2); - AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean, - moduleIdentifier2); + TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory.createModule("", null, null); + ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp", "parallel"); + ObjectName dynON2 = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier2); + AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean, moduleIdentifier2); platformMBeanServer.registerMBean(dyn, dynON2); try { - TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy( - platformMBeanServer, dynON2, + TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy(platformMBeanServer, dynON2, TestingParallelAPSPConfigMXBean.class); - ObjectName withTransactionName = ObjectNameUtil - .createTransactionModuleON("transaction1", "moduleName", "instanceName"); + ObjectName withTransactionName = ObjectNameUtil.createTransactionModuleON("transaction1", "moduleName", + "instanceName"); proxy.setThreadPool(withTransactionName); - ObjectName withoutTransactionName = ObjectNameUtil - .withoutTransactionName(withTransactionName); + ObjectName withoutTransactionName = ObjectNameUtil.withoutTransactionName(withTransactionName); assertEquals(withoutTransactionName, proxy.getThreadPool()); } finally { platformMBeanServer.unregisterMBean(dynON2); @@ -104,8 +91,7 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest { } private void setNumberOfThreads(final int numberOfThreads) throws Exception { - DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, - threadPoolDynamicWrapperON, DynamicMBean.class); + DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class); proxy.setAttribute(new Attribute(THREAD_COUNT, numberOfThreads)); @@ -123,7 +109,5 @@ public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest { } finally { atomicBoolean.set(false); } - } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java index 969192c621..b6cc61e1e3 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -7,34 +7,21 @@ */ package org.opendaylight.controller.config.manager.impl.factoriesresolver; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import java.io.Closeable; import java.util.AbstractMap; -import java.util.Arrays; -import java.util.Dictionary; import java.util.HashMap; -import java.util.List; import java.util.Map; -import org.mockito.Matchers; -import org.mockito.Mockito; import org.opendaylight.controller.config.spi.ModuleFactory; import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver { - private Map> factories; + private final Map> factories; public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) { this.factories = new HashMap<>(list.length); for (ModuleFactory moduleFactory : list) { String moduleName = moduleFactory.getImplementationName(); if (moduleName == null || moduleName.isEmpty()) { - throw new IllegalStateException( - "Invalid implementation name for " + moduleFactory); + throw new IllegalStateException("Invalid implementation name for " + moduleFactory); } Map.Entry conflicting = factories.get(moduleName); if (conflicting == null) { @@ -47,19 +34,8 @@ public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver } } - private static BundleContext mockBundleContext() { - BundleContext bundleContext = Mockito.mock(BundleContext.class); - ServiceRegistration serviceRegistration = mock(ServiceRegistration.class); - doNothing().when(serviceRegistration).unregister(); - doReturn(serviceRegistration).when(bundleContext).registerService( - Matchers.any(String[].class), any(Closeable.class), - any(Dictionary.class)); - return bundleContext; - } - @Override public Map> getAllFactories() { return factories; } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java index 7d426be662..ca21fef902 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -52,7 +52,8 @@ public class BlankTransactionServiceTrackerTest { @Test public void testValidationException() throws Exception { IllegalArgumentException argumentException = new IllegalArgumentException(); - ValidationException validationException = ValidationException.createForSingleException(new ModuleIdentifier("m", "i"), argumentException); + ValidationException validationException = ValidationException + .createForSingleException(new ModuleIdentifier("m", "i"), argumentException); doThrow(validationException).when(blankTx).hit(); tracker.addingService(getMockServiceReference()); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java index cf50098e09..4ac414616b 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -79,6 +79,7 @@ public class BundleContextBackedModuleFactoriesResolverTest { } @Test + @SuppressWarnings("IllegalCatch") public void testDuplicateFactories() throws Exception { doReturn(f1).when(bundleContext).getService(s2); try { diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java index d694e981d6..7d48ad17ed 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -19,14 +19,13 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; + import java.util.Dictionary; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.DependencyResolverFactory; import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; @@ -50,12 +49,8 @@ public class ModuleFactoryBundleTrackerTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - doAnswer(new Answer() { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable { - return getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]); - } - }).when(bundle).loadClass(anyString()); + doAnswer(invocation -> getClass().getClassLoader().loadClass((String) invocation.getArguments()[0])) + .when(bundle).loadClass(anyString()); doReturn("mockBundle").when(bundle).toString(); doReturn(context).when(bundle).getBundleContext(); doReturn(reg).when(context).registerService(anyString(), anyObject(), any(Dictionary.class)); @@ -68,6 +63,7 @@ public class ModuleFactoryBundleTrackerTest { } @Test + @SuppressWarnings("IllegalCatch") public void testRegisterFactoryInstantiateEx() throws Exception { try { ModuleFactoryBundleTracker.registerFactory(WrongConstructorTestingFactory.class.getName(), bundle); @@ -82,6 +78,7 @@ public class ModuleFactoryBundleTrackerTest { } @Test + @SuppressWarnings("IllegalCatch") public void testRegisterFactoryInstantiateExAccess() throws Exception { try { ModuleFactoryBundleTracker.registerFactory(NoAccessConstructorTestingFactory.class.getName(), bundle); @@ -96,6 +93,7 @@ public class ModuleFactoryBundleTrackerTest { } @Test + @SuppressWarnings("IllegalCatch") public void testRegisterFactoryNotExtending() throws Exception { try { ModuleFactoryBundleTracker.registerFactory(NotExtendingTestingFactory.class.getName(), bundle); @@ -108,6 +106,7 @@ public class ModuleFactoryBundleTrackerTest { } @Test + @SuppressWarnings("IllegalCatch") public void testRegisterFactoryNotExisting() throws Exception { try { ModuleFactoryBundleTracker.registerFactory("Unknown class", bundle); @@ -133,6 +132,7 @@ public class ModuleFactoryBundleTrackerTest { } @Test + @SuppressWarnings("IllegalCatch") public void testAddingBundleError() throws Exception { final ModuleFactoryBundleTracker tracker = new ModuleFactoryBundleTracker(blankTxTracker); doReturn(getClass().getResource("/module-factories/module-factory-fail")).when(bundle).getEntry(anyString()); @@ -151,7 +151,8 @@ public class ModuleFactoryBundleTrackerTest { } } - static class NotExtendingTestingFactory {} + static class NotExtendingTestingFactory { + } static class NoAccessConstructorTestingFactory extends TestingFactory { private NoAccessConstructorTestingFactory() { @@ -172,17 +173,20 @@ public class ModuleFactoryBundleTrackerTest { } @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final BundleContext bundleContext) { throw new UnsupportedOperationException(); } @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { throw new UnsupportedOperationException(); } @Override - public boolean isModuleImplementingServiceInterface(final Class serviceInterface) { + public boolean isModuleImplementingServiceInterface( + final Class serviceInterface) { throw new UnsupportedOperationException(); } @@ -192,7 +196,8 @@ public class ModuleFactoryBundleTrackerTest { } @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext bundleContext) { throw new UnsupportedOperationException(); } } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java index d0df7a7104..4de2302beb 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -13,6 +13,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; + import java.util.Dictionary; import org.junit.Before; import org.junit.Test; @@ -37,7 +38,8 @@ public class RefreshingSCPModuleInfoRegistryTest { @Mock SchemaSourceProvider sourceProvider; - @Before public void setUp() throws Exception { + @Before + public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @@ -48,7 +50,8 @@ public class RefreshingSCPModuleInfoRegistryTest { doReturn("string").when(prov).toString(); final BundleContext ctxt = mock(BundleContext.class); final ServiceRegistration servReg = mock(ServiceRegistration.class); - doReturn(servReg).when(ctxt).registerService(any(Class.class), any(SchemaContextProvider.class), any(Dictionary.class)); + doReturn(servReg).when(ctxt).registerService(any(Class.class), any(SchemaContextProvider.class), + any(Dictionary.class)); doReturn(servReg).when(ctxt).registerService(Mockito.anyString(), any(Object.class), any(Dictionary.class)); doNothing().when(servReg).setProperties(any(Dictionary.class)); @@ -59,7 +62,8 @@ public class RefreshingSCPModuleInfoRegistryTest { doReturn("B-runtime-context").when(bindingRuntimeContext).toString(); doReturn(bindingRuntimeContext).when(codecRegistryProvider).getBindingContext(); - final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, classLoadingStrat, this.sourceProvider, codecRegistryProvider, ctxt); + final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, classLoadingStrat, + this.sourceProvider, codecRegistryProvider, ctxt); doNothing().when(servReg).unregister(); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java index 5b19f615bc..e55e4f76b1 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -29,26 +29,21 @@ import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator; import org.opendaylight.controller.config.manager.impl.jmx.HierarchicalRuntimeBeanRegistrationImpl; import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl; -public class RuntimeBeanRegistratorImplTest extends - AbstractLockedPlatformMBeanServerTest { - static final String module1 = "module1"; - static final String INSTANCE_NAME = "instanceName"; +public class RuntimeBeanRegistratorImplTest extends AbstractLockedPlatformMBeanServerTest { + private static final String MODULE1 = "module1"; + private static final String INSTANCE_NAME = "instanceName"; String additionalKey = "key"; String additionalValue = "value"; - Map additionalProperties = ImmutableMap.of(additionalKey, - additionalValue); + Map additionalProperties = ImmutableMap.of(additionalKey, additionalValue); private BaseJMXRegistrator baseJMXRegistrator; private RootRuntimeBeanRegistratorImpl tested; - private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier( - module1, INSTANCE_NAME); + private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(MODULE1, INSTANCE_NAME); @Before public void setUp() { - baseJMXRegistrator = new BaseJMXRegistrator( - ManagementFactory.getPlatformMBeanServer()); - tested = baseJMXRegistrator - .createRuntimeBeanRegistrator(moduleIdentifier); + baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer()); + tested = baseJMXRegistrator.createRuntimeBeanRegistrator(moduleIdentifier); } @After @@ -66,7 +61,7 @@ public class RuntimeBeanRegistratorImplTest extends platformMBeanServer.getMBeanInfo(on); fail(); } catch (final InstanceNotFoundException e) { - + // FIXME: should it be empty? } } @@ -75,13 +70,11 @@ public class RuntimeBeanRegistratorImplTest extends createRoot(); } - private HierarchicalRuntimeBeanRegistrationImpl createRoot() - throws Exception { - HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested - .registerRoot(new TestingRuntimeBean()); + private HierarchicalRuntimeBeanRegistrationImpl createRoot() throws Exception { + HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested.registerRoot(new TestingRuntimeBean()); - ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(module1, - INSTANCE_NAME, Maps. newHashMap()); + ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME, + Maps.newHashMap()); assertEquals(expectedON1, rootRegistration.getObjectName()); checkExists(rootRegistration.getObjectName()); @@ -95,14 +88,12 @@ public class RuntimeBeanRegistratorImplTest extends } private HierarchicalRuntimeBeanRegistration createAdditional( - final HierarchicalRuntimeBeanRegistrationImpl rootRegistration) - throws Exception { + final HierarchicalRuntimeBeanRegistrationImpl rootRegistration) throws Exception { - HierarchicalRuntimeBeanRegistrationImpl registration = rootRegistration - .register(additionalKey, additionalValue, new TestingRuntimeBean()); + HierarchicalRuntimeBeanRegistrationImpl registration = rootRegistration.register(additionalKey, additionalValue, + new TestingRuntimeBean()); - ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(module1, - INSTANCE_NAME, additionalProperties); + ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME, additionalProperties); assertEquals(expectedON1, registration.getObjectName()); checkExists(registration.getObjectName()); @@ -138,12 +129,9 @@ public class RuntimeBeanRegistratorImplTest extends createRoot(); fail(); } catch (final IllegalStateException e) { - assertThat(e.getMessage(), containsString(rootRegistration - .getObjectName().toString())); - assertThat(e.getMessage(), - containsString("Could not register runtime bean")); - assertThat(e.getMessage(), - containsString(moduleIdentifier.toString())); + assertThat(e.getMessage(), containsString(rootRegistration.getObjectName().toString())); + assertThat(e.getMessage(), containsString("Could not register runtime bean")); + assertThat(e.getMessage(), containsString(moduleIdentifier.toString())); } } @@ -153,5 +141,4 @@ public class RuntimeBeanRegistratorImplTest extends platformMBeanServer.unregisterMBean(rootRegistration.getObjectName()); rootRegistration.close(); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java index 5656163cbe..ba105bc09e 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ package org.opendaylight.controller.config.manager.impl.util; import static org.junit.Assert.assertEquals; + import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collections; @@ -45,10 +46,15 @@ public class InterfacesHelperTest { } - @ServiceInterfaceAnnotation(value = "a", osgiRegistrationType = SuperA.class, namespace = "n", revision = "r", localName = "l") - public interface Service extends AbstractServiceInterface{} - @ServiceInterfaceAnnotation(value = "b", osgiRegistrationType = SuperC.class, namespace = "n", revision = "r", localName = "l") - public interface SubService extends Service{} + @ServiceInterfaceAnnotation(value = "a", osgiRegistrationType = + SuperA.class, namespace = "n", revision = "r", localName = "l") + public interface Service extends AbstractServiceInterface { + } + + @ServiceInterfaceAnnotation(value = "b", osgiRegistrationType = + SuperC.class, namespace = "n", revision = "r", localName = "l") + public interface SubService extends Service { + } public abstract class SubClass extends SuperClass implements SubA, Module { @@ -60,16 +66,16 @@ public class InterfacesHelperTest { @Test public void testGetAllInterfaces() { - Set> expected = Sets.> newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class, - SubA.class, Identifiable.class, Module.class); - assertEquals(expected, - InterfacesHelper.getAllInterfaces(SubClass.class)); + Set> expected = Sets.>newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class, SubA.class, + Identifiable.class, Module.class); + assertEquals(expected, InterfacesHelper.getAllInterfaces(SubClass.class)); } @Test public void testGetServiceInterfaces() throws Exception { assertEquals(Collections.>emptySet(), InterfacesHelper.getServiceInterfaces(SubClass.class)); - assertEquals(Sets.>newHashSet(Service.class, SubService.class), InterfacesHelper.getServiceInterfaces(SubClassWithService.class)); + assertEquals(Sets.>newHashSet(Service.class, SubService.class), + InterfacesHelper.getServiceInterfaces(SubClassWithService.class)); } @Test @@ -81,21 +87,20 @@ public class InterfacesHelperTest { @Test public void testGetMXInterfaces() { - Set> expected = Sets.> newHashSet(SuperBMXBean.class, SubA.class); + Set> expected = Sets.>newHashSet(SuperBMXBean.class, SubA.class); assertEquals(expected, InterfacesHelper.getMXInterfaces(SubClass.class)); } @Test - public void testGetAllAbstractServiceInterfaceClasses(){ + public void testGetAllAbstractServiceInterfaceClasses() { Class clazz = TestingScheduledThreadPoolServiceInterface.class; Set> input = new HashSet<>(); input.add(clazz); - Set> result = InterfacesHelper.getAllAbstractServiceInterfaceClasses(input); + Set> result = InterfacesHelper + .getAllAbstractServiceInterfaceClasses(input); Set> expected = ImmutableSet.of((Class) TestingScheduledThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class - ); + TestingThreadPoolServiceInterface.class); assertEquals(expected, result); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java index 77d48f6ac5..6763facae5 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -31,7 +31,8 @@ public class OsgiRegistrationUtilTest { ServiceRegistration registration2 = mockServiceRegistration(); doReturn(registration2).when(bundleContext).registerService(Object.class, "string", null); - AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class, Object.class); + AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class, + Object.class); aggregatedRegister.close(); InOrder inOrder = Mockito.inOrder(registration, registration2); @@ -64,6 +65,5 @@ public class OsgiRegistrationUtilTest { @Test public void testAggregate() throws Exception { - } -} \ No newline at end of file +} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java index 68f6102987..e215d8853a 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -10,8 +10,9 @@ package org.opendaylight.controller.config.manager.testingservices.parallelapsp; import javax.management.ObjectName; import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation; -@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME, osgiRegistrationType = TestingAPSP.class, - namespace = "namespace", revision = "rev", localName = TestingParallelAPSPConfigMXBean.NAME) +@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME, + osgiRegistrationType = TestingAPSP.class, namespace = "namespace", + revision = "rev", localName = TestingParallelAPSPConfigMXBean.NAME) public interface TestingParallelAPSPConfigMXBean { String NAME = "apsp"; @@ -22,9 +23,8 @@ public interface TestingParallelAPSPConfigMXBean { String getSomeParam(); - void setSomeParam(String s); + void setSomeParam(String string); // for reporting. this should be moved to runtime jmx bean Integer getMaxNumberOfThreads(); - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java index 2b012a750c..377a176136 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -18,7 +18,7 @@ import org.opendaylight.controller.config.manager.testingservices.threadpool.Tes @NotThreadSafe public class TestingParallelAPSPImpl implements TestingAPSP, Closeable { public static final int MINIMAL_NUMBER_OF_THREADS = 10; - private TestingThreadPoolIfc threadPool; + private final TestingThreadPoolIfc threadPool; private String someParam; public TestingParallelAPSPImpl(final TestingThreadPoolIfc threadPool, @@ -46,14 +46,13 @@ public class TestingParallelAPSPImpl implements TestingAPSP, Closeable { return threadPool; } - void setSomeParam(final String s) { + void setSomeParam(final String string) { checkArgument(Strings.isNullOrEmpty(someParam) == false, "Parameter 'someParam' is blank"); - this.someParam = s; + this.someParam = string; } public String getSomeParam() { return someParam; } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java index 774ddac4e8..656cf04c28 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -14,7 +14,11 @@ import com.google.common.base.Strings; import java.io.Closeable; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; import javax.management.ObjectName; +import javax.management.ReflectionException; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.JmxAttribute; import org.opendaylight.controller.config.api.ModuleIdentifier; @@ -30,10 +34,8 @@ import org.slf4j.LoggerFactory; * Represents service that has dependency to thread pool. */ @NotThreadSafe -public class TestingParallelAPSPModule implements Module, - TestingParallelAPSPConfigMXBean { - private static final Logger LOG = LoggerFactory - .getLogger(TestingParallelAPSPModule.class); +public class TestingParallelAPSPModule implements Module, TestingParallelAPSPConfigMXBean { + private static final Logger LOG = LoggerFactory.getLogger(TestingParallelAPSPModule.class); private final DependencyResolver dependencyResolver; private final AutoCloseable oldCloseable; @@ -43,10 +45,8 @@ public class TestingParallelAPSPModule implements Module, private TestingParallelAPSPImpl instance; private String someParam; - public TestingParallelAPSPModule(final ModuleIdentifier identifier, - final DependencyResolver dependencyResolver, - @Nullable final AutoCloseable oldCloseable, - @Nullable final TestingParallelAPSPImpl oldInstance) { + public TestingParallelAPSPModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver, + @Nullable final AutoCloseable oldCloseable, @Nullable final TestingParallelAPSPImpl oldInstance) { this.identifier = identifier; this.dependencyResolver = dependencyResolver; this.oldCloseable = oldCloseable; @@ -76,50 +76,50 @@ public class TestingParallelAPSPModule implements Module, @Override public Integer getMaxNumberOfThreads() { - if (instance == null) + if (instance == null) { return null; + } return instance.getMaxNumberOfThreads(); } // this would be generated: - private final JmxAttribute threadPoolONJMXAttribute = new JmxAttribute("threadPoolON"); + private final JmxAttribute threadPoolOnJMXAttribute = new JmxAttribute("threadPoolON"); @Override public void validate() { checkNotNull(threadPoolON, "Parameter 'threadPool' must be set"); - dependencyResolver.validateDependency( - TestingThreadPoolServiceInterface.class, threadPoolON, - threadPoolONJMXAttribute); + dependencyResolver.validateDependency(TestingThreadPoolServiceInterface.class, threadPoolON, + threadPoolOnJMXAttribute); - checkState(Strings.isNullOrEmpty(someParam) == false, - "Parameter 'SomeParam' is blank"); + checkState(Strings.isNullOrEmpty(someParam) == false, "Parameter 'SomeParam' is blank"); // check that calling resolveInstance fails try { - dependencyResolver.resolveInstance(TestingThreadPoolIfc.class, - threadPoolON, threadPoolONJMXAttribute); + dependencyResolver.resolveInstance(TestingThreadPoolIfc.class, threadPoolON, threadPoolOnJMXAttribute); throw new RuntimeException("fail"); } catch (final IllegalStateException e) { - checkState("Commit was not triggered".equals(e.getMessage()), - e.getMessage()); + checkState("Commit was not triggered".equals(e.getMessage()), e.getMessage()); } // test retrieving dependent module's attribute int threadCount; try { - threadCount = (Integer)dependencyResolver.getAttribute(threadPoolON, "ThreadCount"); - } catch (final Exception e) { + threadCount = (Integer) dependencyResolver.getAttribute(threadPoolON, "ThreadCount"); + } catch (final ReflectionException | InstanceNotFoundException | AttributeNotFoundException + | MBeanException e) { throw new IllegalStateException(e); } checkState(threadCount > 0); - TestingThreadPoolConfigMXBean proxy = dependencyResolver.newMXBeanProxy(threadPoolON, TestingThreadPoolConfigMXBean.class); + TestingThreadPoolConfigMXBean proxy = dependencyResolver.newMXBeanProxy(threadPoolON, + TestingThreadPoolConfigMXBean.class); checkState(threadCount == proxy.getThreadCount()); } @Override + @SuppressWarnings("IllegalCatch") public Closeable getInstance() { if (instance == null) { - TestingThreadPoolIfc threadPoolInstance = dependencyResolver - .resolveInstance(TestingThreadPoolIfc.class, threadPoolON, threadPoolONJMXAttribute); + TestingThreadPoolIfc threadPoolInstance = dependencyResolver.resolveInstance(TestingThreadPoolIfc.class, + threadPoolON, threadPoolOnJMXAttribute); if (oldInstance != null) { // changing thread pool is not supported @@ -139,8 +139,7 @@ public class TestingParallelAPSPModule implements Module, throw new RuntimeException(e); } } - instance = new TestingParallelAPSPImpl(threadPoolInstance, - someParam); + instance = new TestingParallelAPSPImpl(threadPoolInstance, someParam); } } return instance; @@ -155,6 +154,4 @@ public class TestingParallelAPSPModule implements Module, public ModuleIdentifier getIdentifier() { return identifier; } - - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java index 3fc07fe571..4ce5dc91dd 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -34,23 +34,21 @@ public class TestingParallelAPSPModuleFactory implements ModuleFactory { @Override public TestingParallelAPSPModule createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - return new TestingParallelAPSPModule(new ModuleIdentifier(NAME, - instanceName), dependencyResolver, null, null); + return new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName), dependencyResolver, null, null); } @Override public TestingParallelAPSPModule createModule(final String instanceName, - final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext context) - throws Exception { + final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, + final BundleContext context) throws Exception { TestingParallelAPSPImpl oldInstance; try { oldInstance = (TestingParallelAPSPImpl) old.getInstance(); } catch (final ClassCastException e) { oldInstance = null; } - TestingParallelAPSPModule result = new TestingParallelAPSPModule( - new ModuleIdentifier(NAME, instanceName), dependencyResolver, - old.getInstance(), oldInstance); + TestingParallelAPSPModule result = new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName), + dependencyResolver, old.getInstance(), oldInstance); // copy attributes String someParam = (String) old.getAttribute("SomeParam"); result.setSomeParam(someParam); @@ -66,7 +64,8 @@ public class TestingParallelAPSPModuleFactory implements ModuleFactory { } @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext context) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext context) { return new HashSet<>(); } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java index 9c550966e6..e6f5490864 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -12,6 +12,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import java.util.Map; import javax.management.ObjectName; import org.junit.After; @@ -36,8 +37,7 @@ public class DependentWiringTest extends AbstractParallelAPSPTest { @Before public void setUp() { super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, - new TestingFixedThreadPoolModuleFactory(), - new TestingParallelAPSPModuleFactory())); + new TestingFixedThreadPoolModuleFactory(), new TestingParallelAPSPModuleFactory())); } @After @@ -54,29 +54,24 @@ public class DependentWiringTest extends AbstractParallelAPSPTest { public void testDependencies() throws Exception { ObjectName apspON; { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); // create fixed1 ObjectName threadPoolTransactionON = createFixed1(transaction, TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS); // create apsp-parallel - ObjectName apspNameTransactionON = createParallelAPSP(transaction, - threadPoolTransactionON); - TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction - .newMXBeanProxy(apspNameTransactionON, TestingParallelAPSPConfigMXBean.class); + ObjectName apspNameTransactionON = createParallelAPSP(transaction, threadPoolTransactionON); + TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction.newMXBeanProxy(apspNameTransactionON, + TestingParallelAPSPConfigMXBean.class); parallelAPSPConfigProxy.setSomeParam("");// trigger validation - // failure + // failure try { transaction.validateConfig(); fail(); } catch (final ValidationException e) { - for (Map.Entry> exception : e - .getFailedValidations().entrySet()) { - for (Map.Entry entry : exception - .getValue().entrySet()) { - assertThat( - entry.getValue().getMessage(), - containsString("Parameter 'SomeParam' is blank")); + for (Map.Entry> exception : e.getFailedValidations() + .entrySet()) { + for (Map.Entry entry : exception.getValue().entrySet()) { + assertThat(entry.getValue().getMessage(), containsString("Parameter 'SomeParam' is blank")); } } } @@ -86,13 +81,11 @@ public class DependentWiringTest extends AbstractParallelAPSPTest { transaction.commit(); fail(); } catch (final ValidationException e) { - for (Map.Entry> exception : e - .getFailedValidations().entrySet()) { - for (Map.Entry entry : exception - .getValue().entrySet()) { + for (Map.Entry> exception : e.getFailedValidations() + .entrySet()) { + for (Map.Entry entry : exception.getValue().entrySet()) { String err = entry.getValue().getMessage(); - assertTrue("Unexpected error message: " + err, - err.contains("Parameter 'SomeParam' is blank")); + assertTrue("Unexpected error message: " + err, err.contains("Parameter 'SomeParam' is blank")); } } } @@ -100,35 +93,30 @@ public class DependentWiringTest extends AbstractParallelAPSPTest { parallelAPSPConfigProxy.setSomeParam("abc");// fix validation // failure transaction.commit(); - apspON = ObjectNameUtil - .withoutTransactionName(apspNameTransactionON); + apspON = ObjectNameUtil.withoutTransactionName(apspNameTransactionON); } // test reported apsp number of threads - TestingParallelAPSPConfigMXBean parallelAPSPRuntimeProxy = configRegistryClient - .newMXBeanProxy(apspON, TestingParallelAPSPConfigMXBean.class); - assertEquals( - (Integer) TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS, + TestingParallelAPSPConfigMXBean parallelAPSPRuntimeProxy = configRegistryClient.newMXBeanProxy(apspON, + TestingParallelAPSPConfigMXBean.class); + assertEquals((Integer) TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS, parallelAPSPRuntimeProxy.getMaxNumberOfThreads()); // next transaction - recreate new thread pool int newNumberOfThreads = TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS * 2; { // start new transaction - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); - ObjectName threadPoolNames_newTx = transaction.lookupConfigBean( - getThreadPoolImplementationName(), fixed1); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); + ObjectName threadPoolNamesNewTx = + transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1); TestingFixedThreadPoolConfigMXBean fixedConfigTransactionProxy = transaction - .newMXBeanProxy(threadPoolNames_newTx, TestingFixedThreadPoolConfigMXBean.class); + .newMXBeanProxy(threadPoolNamesNewTx, TestingFixedThreadPoolConfigMXBean.class); fixedConfigTransactionProxy.setThreadCount(newNumberOfThreads); transaction.commit(); } // new reference should be copied to apsp-parallel - assertEquals((Integer) newNumberOfThreads, - parallelAPSPRuntimeProxy.getMaxNumberOfThreads()); - + assertEquals((Integer) newNumberOfThreads, parallelAPSPRuntimeProxy.getMaxNumberOfThreads()); } @Test @@ -137,10 +125,9 @@ public class DependentWiringTest extends AbstractParallelAPSPTest { ObjectName threadPoolON = createFixed1(transaction, 10); transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1); String refName = "ref"; - ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName, - threadPoolON); + ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, + refName, threadPoolON); createParallelAPSP(transaction, serviceReferenceON); transaction.commit(); - } } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java index 9c0f56b120..459e458384 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -18,24 +18,21 @@ import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans.TestingScheduledRuntimeBean; import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc; -public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, - TestingScheduledThreadPoolIfc, Closeable { +public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, TestingScheduledThreadPoolIfc, Closeable { private static volatile int numberOfCloseMethodCalls = 0; private final ScheduledThreadPoolExecutor executor; private final RootRuntimeBeanRegistrator runtimeBeanRegistrator; - public static final List allExecutors = Lists - .newLinkedList(); + public static final List ALLEXECUTORS = Lists.newLinkedList(); - public TestingScheduledThreadPoolImpl( - final RootRuntimeBeanRegistrator runtimeBeanRegistrator, final int corePoolSize) { + public TestingScheduledThreadPoolImpl(final RootRuntimeBeanRegistrator runtimeBeanRegistrator, + final int corePoolSize) { this.runtimeBeanRegistrator = runtimeBeanRegistrator; executor = new ScheduledThreadPoolExecutor(corePoolSize); - allExecutors.add(executor); + ALLEXECUTORS.add(executor); HierarchicalRuntimeBeanRegistration hierarchicalRuntimeBeanRegistration = runtimeBeanRegistrator .registerRoot(new TestingScheduledRuntimeBean()); - hierarchicalRuntimeBeanRegistration.register("a", "b", - new TestingScheduledRuntimeBean()); + hierarchicalRuntimeBeanRegistration.register("a", "b", new TestingScheduledRuntimeBean()); } @Override @@ -61,15 +58,14 @@ public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, } public static void cleanUp() { - for (ScheduledThreadPoolExecutor executor : allExecutors) { + for (ScheduledThreadPoolExecutor executor : ALLEXECUTORS) { executor.shutdown(); } - allExecutors.clear(); + ALLEXECUTORS.clear(); numberOfCloseMethodCalls = 0; } public static int getNumberOfCloseMethodCalls() { return numberOfCloseMethodCalls; } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java index cf0d9d17df..a16c7c5092 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -23,10 +23,8 @@ import org.opendaylight.controller.config.spi.Module; * This class has two exported interfaces and two runtime beans. Recreation is * triggered by setting Recreate attribute to true. */ -public class TestingScheduledThreadPoolModule implements Module, - TestingScheduledThreadPoolConfigBeanMXBean, - RuntimeBeanRegistratorAwareModule, - TestingScheduledThreadPoolServiceInterface { +public class TestingScheduledThreadPoolModule implements Module, TestingScheduledThreadPoolConfigBeanMXBean, + RuntimeBeanRegistratorAwareModule, TestingScheduledThreadPoolServiceInterface { private final ModuleIdentifier identifier; @Nullable @@ -40,16 +38,14 @@ public class TestingScheduledThreadPoolModule implements Module, private boolean recreate; public TestingScheduledThreadPoolModule(final ModuleIdentifier identifier, - @Nullable final AutoCloseable oldCloseable, - @Nullable final TestingScheduledThreadPoolImpl oldInstance) { + @Nullable final AutoCloseable oldCloseable, @Nullable final TestingScheduledThreadPoolImpl oldInstance) { this.identifier = identifier; this.oldCloseable = oldCloseable; this.oldInstance = oldInstance; } @Override - public void setRuntimeBeanRegistrator( - final RootRuntimeBeanRegistrator runtimeBeanRegistrator) { + public void setRuntimeBeanRegistrator(final RootRuntimeBeanRegistrator runtimeBeanRegistrator) { this.runtimeBeanRegistrator = runtimeBeanRegistrator; } @@ -57,14 +53,13 @@ public class TestingScheduledThreadPoolModule implements Module, public void validate() { assertNull(runtimeBeanRegistrator); // check thread count - checkState(threadCount > 0, - "Parameter 'ThreadCount' must be greater than 0"); + checkState(threadCount > 0, "Parameter 'ThreadCount' must be greater than 0"); } @Override public boolean canReuse(final Module oldModule) { - return getClass().isInstance(oldModule) && getThreadCount() == - ((TestingScheduledThreadPoolModule) oldModule).getThreadCount(); + return getClass().isInstance(oldModule) + && getThreadCount() == ((TestingScheduledThreadPoolModule) oldModule).getThreadCount(); } @Override @@ -78,6 +73,7 @@ public class TestingScheduledThreadPoolModule implements Module, } @Override + @SuppressWarnings("IllegalCatch") public Closeable getInstance() { assertNotNull(runtimeBeanRegistrator); if (instance == null) { @@ -94,8 +90,7 @@ public class TestingScheduledThreadPoolModule implements Module, } } // close old threadpool and esp. unregister runtime beans - instance = new TestingScheduledThreadPoolImpl( - runtimeBeanRegistrator, threadCount); + instance = new TestingScheduledThreadPoolImpl(runtimeBeanRegistrator, threadCount); } } return instance; @@ -116,6 +111,4 @@ public class TestingScheduledThreadPoolModule implements Module, public ModuleIdentifier getIdentifier() { return identifier; } - - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java index 7428776b76..1011951055 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -26,7 +26,7 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { private static Set> ifc = ImmutableSet.of( (Class) TestingScheduledThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class); + TestingThreadPoolServiceInterface.class); @Override public boolean isModuleImplementingServiceInterface( @@ -40,33 +40,32 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { } @Override - public Module createModule(final String instanceName, - final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, - instanceName), null, null); + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final BundleContext bundleContext) { + return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null); } @Override - public Module createModule(final String instanceName, - final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) - throws Exception { + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { TestingScheduledThreadPoolImpl oldInstance; try { oldInstance = (TestingScheduledThreadPoolImpl) old.getInstance(); - } catch (final ClassCastException e) {// happens after OSGi update + } catch (final ClassCastException e) { + // happens after OSGi update oldInstance = null; } TestingScheduledThreadPoolModule configBean = new TestingScheduledThreadPoolModule( - new ModuleIdentifier(NAME, instanceName), old.getInstance(), - oldInstance); + new ModuleIdentifier(NAME, instanceName), old.getInstance(), oldInstance); // copy attributes configBean.setRecreate((Boolean) old.getAttribute("Recreate")); return configBean; } @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext bundleContext) { return new HashSet<>(); } @@ -74,6 +73,4 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { public Set> getImplementedServiceIntefaces() { return ifc; } - - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java index 998627ede2..aac933cf29 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java @@ -1,12 +1,14 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ /** - * Tests config bean that exports two independent interfaces - {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc} and + * Tests config bean that exports two independent interfaces - + * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc} + * and * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}. */ package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java index f686d27ef4..2a9aa16088 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -19,7 +19,7 @@ import org.opendaylight.controller.config.manager.testingservices.scheduledthrea import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory; public abstract class AbstractScheduledTest extends AbstractConfigTest { - protected static final String scheduled1 = "scheduled1"; + protected static final String SCHEDULED1 = "scheduled1"; @Before public final void setUp() { diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java index 7b975ceb20..12753002af 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -30,9 +30,11 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; /** * TestingScheduledThreadPool exports 2 interfaces:
- * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME} + * {@link org.opendaylight.controller.config.manager.testingservices + * .scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME} * ,
- * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME} + * {@link org.opendaylight.controller.config.manager + * .testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME} *
*
* It also exports 2 runtime beans, one default and one with additional @@ -40,25 +42,21 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; */ public class RuntimeBeanTest extends AbstractScheduledTest { - ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1, - Maps. newHashMap()); + ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME, + SCHEDULED1, Maps.newHashMap()); // additional runtime bean - ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1, - ImmutableMap.of("a", "b")); + ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME, + SCHEDULED1, ImmutableMap.of("a", "b")); - List allObjectNames = Lists.newArrayList(ifc1runtimeON1, - ifc1runtimeON2); + List allObjectNames = Lists.newArrayList(ifc1runtimeON1, ifc1runtimeON2); - private ObjectName createScheduled() throws InstanceAlreadyExistsException, - ConflictingVersionException, ValidationException { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + private ObjectName createScheduled() + throws InstanceAlreadyExistsException, ConflictingVersionException, ValidationException { + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); // create using TestingThreadPoolIfc: - ObjectName createdConfigBean = transaction.createModule( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + ObjectName createdConfigBean = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, + SCHEDULED1); // commit transaction.commit(); return createdConfigBean; @@ -93,27 +91,21 @@ public class RuntimeBeanTest extends AbstractScheduledTest { @Test public void testLookup() throws Exception { createScheduled(); - assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2), - configRegistryClient.lookupRuntimeBeans()); + assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2), configRegistryClient.lookupRuntimeBeans()); } @Test public void testReuse() throws Exception { ObjectName createdConfigBean = createScheduled(); // empty transaction - CommitStatus commitInfo = configRegistryClient.createTransaction() - .commit(); + CommitStatus commitInfo = configRegistryClient.createTransaction().commit(); // check that it was reused - ObjectName readableConfigBean = ObjectNameUtil - .withoutTransactionName(createdConfigBean); - List newInstances = Collections. emptyList(); - List reusedInstances = Lists - .newArrayList(readableConfigBean); - List recreatedInstaces = Collections - . emptyList(); - assertEquals(new CommitStatus(newInstances, reusedInstances, - recreatedInstaces), commitInfo); + ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean); + List newInstances = Collections.emptyList(); + List reusedInstances = Lists.newArrayList(readableConfigBean); + List recreatedInstaces = Collections.emptyList(); + assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo); checkRuntimeBeans(); } @@ -121,37 +113,31 @@ public class RuntimeBeanTest extends AbstractScheduledTest { public void testRecreate() throws Exception { ObjectName createdConfigBean = createScheduled(); // empty transaction - ConfigTransactionJMXClient configTransaction = configRegistryClient - .createTransaction(); - ObjectName scheduledWritableON = configTransaction.lookupConfigBean( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction(); + ObjectName scheduledWritableON = configTransaction + .lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); TestingScheduledThreadPoolConfigBeanMXBean scheduledWritableProxy = configTransaction .newMXBeanProxy(scheduledWritableON, TestingScheduledThreadPoolConfigBeanMXBean.class); scheduledWritableProxy.setRecreate(true); CommitStatus commitInfo = configTransaction.commit(); // check that it was recreated - ObjectName readableConfigBean = ObjectNameUtil - .withoutTransactionName(createdConfigBean); - List newInstances = Collections. emptyList(); - List reusedInstances = Collections. emptyList(); - List recreatedInstaces = Lists - .newArrayList(readableConfigBean); - assertEquals(new CommitStatus(newInstances, reusedInstances, - recreatedInstaces), commitInfo); + ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean); + List newInstances = Collections.emptyList(); + List reusedInstances = Collections.emptyList(); + List recreatedInstaces = Lists.newArrayList(readableConfigBean); + assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo); checkRuntimeBeans(); } @Test public void testDestroy_shouldUnregisterRuntimeBeans() throws Exception { ObjectName createdConfigBean = createScheduled(); - ConfigTransactionJMXClient configTransaction = configRegistryClient - .createTransaction(); - configTransaction.destroyModule(ObjectNameUtil - .createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean)); + ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction(); + configTransaction.destroyModule( + ObjectNameUtil.createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean)); configTransaction.commit(); for (ObjectName on : allObjectNames) { checkRuntimeBeanDoesNotExist(on); } } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java index 2a7876255f..9c6ba0700c 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -31,24 +31,21 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; public class TwoInterfacesExportTest extends AbstractScheduledTest { - private void assertExists(final String moduleName, final String instanceName) - throws Exception { + private void assertExists(final String moduleName, final String instanceName) throws Exception { assertExists(null, moduleName, instanceName); } - private void assertExists(@Nullable final ConfigTransactionJMXClient transaction, - final String moduleName, final String instanceName) - throws InstanceNotFoundException, IntrospectionException, ReflectionException { + private void assertExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName, + final String instanceName) throws InstanceNotFoundException, IntrospectionException, ReflectionException { if (transaction != null) { transaction.lookupConfigBean(moduleName, instanceName); // make a dummy call - platformMBeanServer.getMBeanInfo(ObjectNameUtil.createTransactionModuleON( - transaction.getTransactionName(), moduleName, instanceName)); + platformMBeanServer.getMBeanInfo(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), + moduleName, instanceName)); } else { configRegistryClient.lookupConfigBean(moduleName, instanceName); // make a dummy call - platformMBeanServer.getMBeanInfo(ObjectNameUtil.createReadOnlyModuleON(moduleName, - instanceName)); + platformMBeanServer.getMBeanInfo(ObjectNameUtil.createReadOnlyModuleON(moduleName, instanceName)); } } @@ -56,123 +53,105 @@ public class TwoInterfacesExportTest extends AbstractScheduledTest { assertNotExists(null, moduleName, instanceName); } - private void assertNotExists( - @Nullable final ConfigTransactionJMXClient transaction, - final String moduleName, final String instanceName) { + private void assertNotExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName, + final String instanceName) { if (transaction != null) { try { transaction.lookupConfigBean(moduleName, instanceName); fail(); } catch (final InstanceNotFoundException e) { - + // FIXME: should be empty? } } else { try { configRegistryClient.lookupConfigBean(moduleName, instanceName); fail(); } catch (final InstanceNotFoundException e) { - + // FIXME: should be empty? } } } @Test public void twoInterfaceNamesAfterCreatingConfigBean() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); // create using TestingThreadPoolIfc: - ObjectName scheduled1name = transaction.createModule( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + ObjectName scheduled1name = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); - ObjectName retrievedName = transaction.lookupConfigBean( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + ObjectName retrievedName = transaction.lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME, + SCHEDULED1); assertEquals(scheduled1name, retrievedName); // getExistingConfigBean should resolve moduleName String moduleName = TestingScheduledThreadPoolModuleFactory.NAME; - retrievedName = transaction.lookupConfigBean(moduleName, scheduled1); - ObjectName expected = ObjectNameUtil.createTransactionModuleON( - transaction.getTransactionName(), moduleName, scheduled1); + retrievedName = transaction.lookupConfigBean(moduleName, SCHEDULED1); + ObjectName expected = ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName, + SCHEDULED1); assertEquals(expected, retrievedName); // commit transaction.commit(); - assertEquals(1, TestingScheduledThreadPoolImpl.allExecutors.size()); - assertFalse(TestingScheduledThreadPoolImpl.allExecutors.get(0) - .isTerminated()); - assertEquals(0, - TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls()); + assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size()); + assertFalse(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated()); + assertEquals(0, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls()); - assertExists(moduleName, scheduled1); + assertExists(moduleName, SCHEDULED1); // destroy using ThreadPool ifc transaction = configRegistryClient.createTransaction(); - transaction.destroyModule(ObjectNameUtil.createTransactionModuleON( - transaction.getTransactionName(), moduleName, scheduled1)); + transaction.destroyModule( + ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName, SCHEDULED1)); transaction.commit(); - assertEquals(1, TestingScheduledThreadPoolImpl.allExecutors.size()); - assertTrue(TestingScheduledThreadPoolImpl.allExecutors.get(0) - .isTerminated()); - assertEquals(1, - TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls()); + assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size()); + assertTrue(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated()); + assertEquals(1, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls()); // should not be in platform: - assertNotExists(moduleName, scheduled1); + assertNotExists(moduleName, SCHEDULED1); transaction = configRegistryClient.createTransaction(); // should not be in transaction - assertNotExists(transaction, moduleName, scheduled1); + assertNotExists(transaction, moduleName, SCHEDULED1); } @Test - public void tryToRegisterThreadPoolWithSameName() - throws InstanceAlreadyExistsException { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + public void tryToRegisterThreadPoolWithSameName() throws InstanceAlreadyExistsException { + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); - transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, - scheduled1); + transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); try { - transaction.createModule( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); fail(); } catch (final InstanceAlreadyExistsException e) { - assertThat( - e.getMessage(), - containsString("There is an instance registered with name ModuleIdentifier{factoryName='scheduled', instanceName='scheduled1'}")); + assertThat(e.getMessage(), containsString( + "There is an instance registered with name " + + "ModuleIdentifier{factoryName='scheduled', instanceName='scheduled1'}")); } } // -- @Test public void testRegisteringAllIfcNames() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); - transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, - scheduled1); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); + transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); transaction.commit(); - assertExists(TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); + assertExists(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); // another transaction transaction = configRegistryClient.createTransaction(); - assertExists(transaction, TestingScheduledThreadPoolModuleFactory.NAME, - scheduled1); + assertExists(transaction, TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); } @Test - public void testWithAPSP_useScheduledNames() - throws InstanceAlreadyExistsException, ValidationException { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); - ObjectName scheduledName = transaction.createModule( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1); - - ObjectName apspName = transaction.createModule( - TestingParallelAPSPModuleFactory.NAME, "apsp1"); - TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy( - apspName, TestingParallelAPSPConfigMXBean.class); + public void testWithAPSP_useScheduledNames() throws InstanceAlreadyExistsException, ValidationException { + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); + ObjectName scheduledName = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); + + ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1"); + TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName, + TestingParallelAPSPConfigMXBean.class); apspProxy.setThreadPool(scheduledName); apspProxy.setSomeParam("someParam"); transaction.validateConfig(); @@ -181,17 +160,14 @@ public class TwoInterfacesExportTest extends AbstractScheduledTest { @Test public void testWithAPSP_useIfcNameMismatch() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); - transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, - scheduled1); - - ObjectName apspName = transaction.createModule( - TestingParallelAPSPModuleFactory.NAME, "apsp1"); - TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy( - apspName, TestingParallelAPSPConfigMXBean.class); - apspProxy.setThreadPool(ObjectNameUtil.createReadOnlyModuleON( - TestingScheduledThreadPoolModuleFactory.NAME, scheduled1)); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); + transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1); + + ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1"); + TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName, + TestingParallelAPSPConfigMXBean.class); + apspProxy.setThreadPool( + ObjectNameUtil.createReadOnlyModuleON(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1)); apspProxy.setSomeParam("someParam"); transaction.validateConfig(); transaction.commit(); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java index 5c30d1e977..b87f3cd077 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -10,8 +10,8 @@ package org.opendaylight.controller.config.manager.testingservices.seviceinterfa import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation; import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingModifiableThreadPoolIfc; -@ServiceInterfaceAnnotation(value = "fqn:modifiable-threadpool", osgiRegistrationType = TestingModifiableThreadPoolIfc.class, - namespace = "foo", revision = "bar", localName = "modifiable-threadpool") -public interface ModifiableThreadPoolServiceInterface extends - TestingThreadPoolServiceInterface { +@ServiceInterfaceAnnotation(value = "fqn:modifiable-threadpool", + osgiRegistrationType = TestingModifiableThreadPoolIfc.class, + namespace = "foo", revision = "bar", localName = "modifiable-threadpool") +public interface ModifiableThreadPoolServiceInterface extends TestingThreadPoolServiceInterface { } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java index 2d99b25e0a..66fdf301d3 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -11,9 +11,9 @@ import org.opendaylight.controller.config.api.annotations.AbstractServiceInterfa import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation; import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc; -@ServiceInterfaceAnnotation(value = TestingThreadPoolServiceInterface.QNAME, osgiRegistrationType = TestingThreadPoolIfc.class, +@ServiceInterfaceAnnotation(value = TestingThreadPoolServiceInterface.QNAME, + osgiRegistrationType = TestingThreadPoolIfc.class, namespace = "ns", revision = "foo", localName = "testing-threadpool") -public interface TestingThreadPoolServiceInterface extends - AbstractServiceInterface { +public interface TestingThreadPoolServiceInterface extends AbstractServiceInterface { String QNAME = "(ns?revision=foo)testing-threadpool"; } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java index 4f8de6dfe1..35413a1b1f 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -26,14 +26,14 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable, private final String uniqueName; public static void cleanUp() { - for (ExecutorService executorService : allExecutors) { + for (ExecutorService executorService : ALL_EXECUTORS) { executorService.shutdown(); } - allExecutors.clear(); + ALL_EXECUTORS.clear(); } // for verification purposes: - public static final List allExecutors = Collections + public static final List ALL_EXECUTORS = Collections .synchronizedList(Lists.newLinkedList()); public TestingFixedThreadPool(final int threadCount, final String uniqueName) { @@ -41,7 +41,7 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable, this.uniqueName = uniqueName; executorService = (ThreadPoolExecutor) Executors .newFixedThreadPool(threadCount); - allExecutors.add(executorService); + ALL_EXECUTORS.add(executorService); } @Override @@ -52,7 +52,7 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable, @Override public void close() throws IOException { executorService.shutdown(); - allExecutors.remove(executorService); + ALL_EXECUTORS.remove(executorService); } @@ -70,5 +70,4 @@ public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable, checkArgument(activeCount > 0); executorService.setMaximumPoolSize(activeCount); } - } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java index a6c9b59605..8ac0c32223 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -35,7 +35,6 @@ public class TestingFixedThreadPoolModule implements this.oldInstance = oldInstance; } - // attributes @Override public void setThreadCount(final int threadCount) { @@ -75,6 +74,7 @@ public class TestingFixedThreadPoolModule implements } @Override + @SuppressWarnings("IllegalCatch") public Closeable getInstance() { if (instance == null) { if (isReusable() && triggerNewInstanceCreation == false) { // simulate diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java index e78ae98009..5975ce141e 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -21,10 +21,11 @@ import org.opendaylight.controller.config.spi.Module; import org.opendaylight.controller.config.spi.ModuleFactory; import org.osgi.framework.BundleContext; -public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory implements ModuleFactory { +public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory + implements ModuleFactory { public static final String NAME = "fixed"; - private static final Set> ifc = ImmutableSet.of( + private static final Set> IFC = ImmutableSet.of( (Class) ModifiableThreadPoolServiceInterface.class, TestingThreadPoolServiceInterface.class); @@ -36,14 +37,12 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr @Override public TestingFixedThreadPoolModule createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, - instanceName), null, null); + return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null); } @Override - public Module createModule(final String instanceName, - final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) - throws Exception { + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { int threadCount = (Integer) old.getAttribute("ThreadCount"); // is the instance compatible? TestingFixedThreadPool oldInstance; @@ -54,9 +53,8 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr // old instance will be closed, new needs to be created oldInstance = null; } - TestingFixedThreadPoolModule result = new TestingFixedThreadPoolModule( - new ModuleIdentifier(NAME, instanceName), old.getInstance(), - oldInstance); + TestingFixedThreadPoolModule result = new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName), + old.getInstance(), oldInstance); result.setThreadCount(threadCount); return result; } @@ -64,16 +62,17 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr @Override public boolean isModuleImplementingServiceInterface( final Class serviceInterface) { - return ifc.contains(serviceInterface); + return IFC.contains(serviceInterface); } @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext bundleContext) { return new HashSet<>(); } @Override public Set> getImplementedServiceIntefaces() { - return ifc; + return IFC; } } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java index bd75a703d7..dc1bdf4b02 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -7,7 +7,8 @@ */ /** * Represents simple service that has getters and setters, but no dependencies. - * Creates fixed thread pool wrapped in {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}. + * Creates fixed thread pool wrapped in {@link org.opendaylight + * .controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}. * Supports changing the number of threads on 'live' executor. */ package org.opendaylight.controller.config.manager.testingservices.threadpool; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java index e047a1ecca..9198c4b8a9 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -29,7 +29,8 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; import org.osgi.framework.BundleContext; public class ShutdownTest extends AbstractConfigTest { - private final TestingFixedThreadPoolModuleFactory testingFixedThreadPoolModuleFactory = new TestingFixedThreadPoolModuleFactory(); + private final TestingFixedThreadPoolModuleFactory testingFixedThreadPoolModuleFactory = + new TestingFixedThreadPoolModuleFactory(); @Mock ModuleFactoriesResolver mockedResolver; @@ -44,7 +45,6 @@ public class ShutdownTest extends AbstractConfigTest { super.initConfigTransactionManagerImpl(mockedResolver); } - @Test public void testCreateAndDestroyBeanInSameTransaction() throws Exception { { @@ -52,12 +52,12 @@ public class ShutdownTest extends AbstractConfigTest { SimpleConfigurationTest.createFixedThreadPool(transaction); transaction.commit(); } - assertEquals(1, TestingFixedThreadPool.allExecutors.size()); + assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size()); doReturn(Collections.emptyMap()).when(mockedResolver).getAllFactories(); { ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); transaction.commit(); } - assertEquals(1, TestingFixedThreadPool.allExecutors.size()); + assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size()); } } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java index d837ffcdb4..f2dc012bc8 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -22,6 +22,7 @@ import java.util.Set; import java.util.concurrent.ThreadPoolExecutor; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; +import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.ObjectName; import javax.management.ReflectionException; @@ -55,20 +56,18 @@ import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; * dependencies. */ public class SimpleConfigurationTest extends AbstractConfigTest { - private static final int numberOfThreads = 5; - private final int numberOfThreads2 = 10; - private static final String fixed1 = "fixed1"; - private static final List emptyONs = Collections - . emptyList(); - private static final ObjectName platformFixed1ON = ObjectNameUtil - .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, fixed1); - private static final List fixed1List = Arrays - .asList(platformFixed1ON); + private static final int NUMBER_OF_THREADS = 5; + private static final int NUMBER_OF_THREADS2 = 10; + private static final String FIXED1 = "fixed1"; + private static final List EMPTYO_NS = Collections.emptyList(); + private static final ObjectName PLATFORM_FIXED1ON = ObjectNameUtil + .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); + private static final List FIXED1_LIST = Arrays.asList(PLATFORM_FIXED1ON); @Before public void setUp() { - super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, - new TestingFixedThreadPoolModuleFactory())); + super.initConfigTransactionManagerImpl( + new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory())); } @After @@ -77,8 +76,7 @@ public class SimpleConfigurationTest extends AbstractConfigTest { } private ObjectName firstCommit() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); ObjectName fixed1names = createFixedThreadPool(transaction); @@ -86,36 +84,32 @@ public class SimpleConfigurationTest extends AbstractConfigTest { assertEquals(1, configRegistryClient.getOpenConfigs().size()); CommitStatus commitStatus = transaction.commit(); assertEquals(0, configRegistryClient.getOpenConfigs().size()); - CommitStatus expected = new CommitStatus(Arrays.asList(ObjectNameUtil - .withoutTransactionName(fixed1names)), emptyONs, emptyONs); + CommitStatus expected = new CommitStatus(Arrays.asList(ObjectNameUtil.withoutTransactionName(fixed1names)), + EMPTYO_NS, EMPTYO_NS); assertEquals(expected, commitStatus); - assertEquals(1, TestingFixedThreadPool.allExecutors.size()); - assertFalse(TestingFixedThreadPool.allExecutors.get(0).isShutdown()); + assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size()); + assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown()); return fixed1names; } - static ObjectName createFixedThreadPool( - final ConfigTransactionJMXClient transaction) + static ObjectName createFixedThreadPool(final ConfigTransactionJMXClient transaction) throws InstanceAlreadyExistsException, InstanceNotFoundException { transaction.assertVersion(0, 1); - ObjectName fixed1names = transaction.createModule( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); - TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction - .newMXBeanProxy(fixed1names, TestingFixedThreadPoolConfigMXBean.class); - fixedConfigProxy.setThreadCount(numberOfThreads); + ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); + TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1names, + TestingFixedThreadPoolConfigMXBean.class); + fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS); - ObjectName retrievedNames = transaction.lookupConfigBean( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); + ObjectName retrievedNames = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); assertEquals(fixed1names, retrievedNames); return fixed1names; } @Test public void testCreateAndDestroyBeanInSameTransaction() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); ObjectName fixed1names = createFixedThreadPool(transaction); transaction.destroyModule(fixed1names); CommitStatus commitStatus = transaction.commit(); @@ -125,21 +119,16 @@ public class SimpleConfigurationTest extends AbstractConfigTest { @Test public void testValidationUsingJMXClient() throws Exception { - ConfigTransactionClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionClient transaction = configRegistryClient.createTransaction(); testValidation(transaction); } - - private static void testValidation(final ConfigTransactionClient transaction) - throws InstanceAlreadyExistsException, ReflectionException, - InstanceNotFoundException, MBeanException, ConflictingVersionException { - ObjectName fixed1names = transaction.createModule( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); + private static void testValidation(final ConfigTransactionClient transaction) throws InstanceAlreadyExistsException, + ReflectionException, InstanceNotFoundException, MBeanException, ConflictingVersionException { + ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); // call validate on config bean try { - platformMBeanServer.invoke(fixed1names, "validate", new Object[0], - new String[0]); + platformMBeanServer.invoke(fixed1names, "validate", new Object[0], new String[0]); fail(); } catch (final MBeanException e) { Exception targetException = e.getTargetException(); @@ -152,13 +141,10 @@ public class SimpleConfigurationTest extends AbstractConfigTest { transaction.validateBean(fixed1names); fail(); } catch (final ValidationException e) { - for (Map.Entry> exception : e - .getFailedValidations().entrySet()) { - for (Map.Entry entry : exception - .getValue().entrySet()) { - assertEquals( - "Parameter 'threadCount' must be greater than 0", - entry.getValue().getMessage()); + for (Map.Entry> exception : e.getFailedValidations() + .entrySet()) { + for (Map.Entry entry : exception.getValue().entrySet()) { + assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage()); } } } @@ -167,26 +153,20 @@ public class SimpleConfigurationTest extends AbstractConfigTest { transaction.validateConfig(); fail(); } catch (final ValidationException e) { - for (Map.Entry> exception : e - .getFailedValidations().entrySet()) { - for (Map.Entry entry : exception - .getValue().entrySet()) { - assertEquals( - "Parameter 'threadCount' must be greater than 0", - entry.getValue().getMessage()); + for (Map.Entry> exception : e.getFailedValidations() + .entrySet()) { + for (Map.Entry entry : exception.getValue().entrySet()) { + assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage()); } } } try { transaction.commit(); } catch (final ValidationException e) { - for (Map.Entry> exception : e - .getFailedValidations().entrySet()) { - for (Map.Entry entry : exception - .getValue().entrySet()) { - assertEquals( - "Parameter 'threadCount' must be greater than 0", - entry.getValue().getMessage()); + for (Map.Entry> exception : e.getFailedValidations() + .entrySet()) { + for (Map.Entry entry : exception.getValue().entrySet()) { + assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage()); } } } @@ -195,14 +175,13 @@ public class SimpleConfigurationTest extends AbstractConfigTest { @Test public void test_createThreadPool_changeNumberOfThreads() throws Exception { firstCommit(); - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction); - assertEquals(numberOfThreads, fixedConfigProxy.getThreadCount()); - fixedConfigProxy.setThreadCount(numberOfThreads2); + assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount()); + fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2); CommitStatus commitStatus = transaction.commit(); - checkThreadPools(1, numberOfThreads2); - CommitStatus expected = new CommitStatus(emptyONs, fixed1List, emptyONs); + checkThreadPools(1, NUMBER_OF_THREADS2); + CommitStatus expected = new CommitStatus(EMPTYO_NS, FIXED1_LIST, EMPTYO_NS); assertEquals(expected, commitStatus); } @@ -214,42 +193,39 @@ public class SimpleConfigurationTest extends AbstractConfigTest { // 2, check that configuration was copied to platform ObjectName on = ObjectNameUtil.withoutTransactionName(fixed1name); platformMBeanServer.getMBeanInfo(on); - assertEquals(numberOfThreads, platformMBeanServer.getAttribute(on, "ThreadCount")); + assertEquals(NUMBER_OF_THREADS, platformMBeanServer.getAttribute(on, "ThreadCount")); // 3, shutdown fixed1 in new transaction - assertFalse(TestingFixedThreadPool.allExecutors.get(0).isShutdown()); - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown()); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); // check versions transaction.assertVersion(1, 2); // test that it was copied to new transaction - ObjectName retrievedName = transaction.lookupConfigBean( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); + ObjectName retrievedName = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); assertNotNull(retrievedName); // check that number of threads was copied from dynamic - TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction - .newMXBeanProxy(retrievedName, TestingFixedThreadPoolConfigMXBean.class); - assertEquals(numberOfThreads, fixedConfigProxy.getThreadCount()); + TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(retrievedName, + TestingFixedThreadPoolConfigMXBean.class); + assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount()); // destroy - transaction.destroyModule(ObjectNameUtil.createTransactionModuleON( - transaction.getTransactionName(), - TestingFixedThreadPoolModuleFactory.NAME, fixed1)); + transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), + TestingFixedThreadPoolModuleFactory.NAME, FIXED1)); transaction.commit(); // 4, check assertEquals(2, configRegistryClient.getVersion()); - assertEquals(0, TestingFixedThreadPool.allExecutors.size()); + assertEquals(0, TestingFixedThreadPool.ALL_EXECUTORS.size()); // dynamic config should be removed from platform try { platformMBeanServer.getMBeanInfo(on); fail(); - } catch (final Exception e) { + } catch (final ReflectionException | InstanceNotFoundException | IntrospectionException e) { assertTrue(e instanceof InstanceNotFoundException); } } @@ -259,36 +235,30 @@ public class SimpleConfigurationTest extends AbstractConfigTest { // 1, start transaction, create new fixed thread pool firstCommit(); // destroy and recreate with different # of threads - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); - - transaction.destroyModule(ObjectNameUtil.createTransactionModuleON( - transaction.getTransactionName(), - TestingFixedThreadPoolModuleFactory.NAME, fixed1)); - - ObjectName fixed1name = transaction.createModule( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); - TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction - .newMXBeanProxy(fixed1name, TestingFixedThreadPoolConfigMXBean.class); - fixedConfigProxy.setThreadCount(numberOfThreads2); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); + + transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), + TestingFixedThreadPoolModuleFactory.NAME, FIXED1)); + + ObjectName fixed1name = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); + TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name, + TestingFixedThreadPoolConfigMXBean.class); + fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2); // commit transaction.commit(); // check that first threadpool is closed - checkThreadPools(1, numberOfThreads2); + checkThreadPools(1, NUMBER_OF_THREADS2); } private static void checkThreadPools(final int expectedTotalNumberOfExecutors, final int expectedNumberOfThreadsInLastExecutor) { - assertEquals(expectedTotalNumberOfExecutors, - TestingFixedThreadPool.allExecutors.size()); + assertEquals(expectedTotalNumberOfExecutors, TestingFixedThreadPool.ALL_EXECUTORS.size()); for (int i = 0; i < expectedTotalNumberOfExecutors - 1; i++) { - assertTrue(TestingFixedThreadPool.allExecutors.get(i).isShutdown()); + assertTrue(TestingFixedThreadPool.ALL_EXECUTORS.get(i).isShutdown()); } - ThreadPoolExecutor lastExecutor = TestingFixedThreadPool.allExecutors - .get(expectedTotalNumberOfExecutors - 1); + ThreadPoolExecutor lastExecutor = TestingFixedThreadPool.ALL_EXECUTORS.get(expectedTotalNumberOfExecutors - 1); assertFalse(lastExecutor.isShutdown()); - assertEquals(expectedNumberOfThreadsInLastExecutor, - lastExecutor.getMaximumPoolSize()); + assertEquals(expectedNumberOfThreadsInLastExecutor, lastExecutor.getMaximumPoolSize()); } @Test @@ -296,34 +266,31 @@ public class SimpleConfigurationTest extends AbstractConfigTest { // 1, start transaction, create new fixed thread pool firstCommit(); // switch boolean to create new instance - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction); fixedConfigProxy.setTriggerNewInstanceCreation(true); // commit CommitStatus commitStatus = transaction.commit(); // check that new threadpool is created and old one is closed - checkThreadPools(1, numberOfThreads); - CommitStatus expected = new CommitStatus(emptyONs, emptyONs, fixed1List); + checkThreadPools(1, NUMBER_OF_THREADS); + CommitStatus expected = new CommitStatus(EMPTYO_NS, EMPTYO_NS, FIXED1_LIST); assertEquals(expected, commitStatus); } // return MBeanProxy for 'fixed1' and current transaction private static TestingFixedThreadPoolConfigMXBean startReconfiguringFixed1ThreadPool( final ConfigTransactionJMXClient transaction) throws InstanceNotFoundException { - ObjectName fixed1name = transaction.lookupConfigBean( - TestingFixedThreadPoolModuleFactory.NAME, fixed1); + ObjectName fixed1name = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); - TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction - .newMXBeanProxy(fixed1name, TestingFixedThreadPoolConfigMXBean.class); + TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name, + TestingFixedThreadPoolConfigMXBean.class); return fixedConfigProxy; } @Test public void testAbort() throws Exception { - ConfigTransactionJMXClient transaction = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction(); assertEquals(1, configRegistryClient.getOpenConfigs().size()); transaction.abortConfig(); @@ -331,48 +298,40 @@ public class SimpleConfigurationTest extends AbstractConfigTest { try { platformMBeanServer.getMBeanInfo(transaction.getObjectName()); fail(); - }catch(final InstanceNotFoundException e){ - assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction", e.getMessage()); + } catch (final InstanceNotFoundException e) { + assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction", + e.getMessage()); } } @Test public void testOptimisticLock_ConfigTransactionClient() throws Exception { - ConfigTransactionJMXClient transaction1 = configRegistryClient - .createTransaction(); - ConfigTransactionJMXClient transaction2 = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction(); + ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction(); transaction2.assertVersion(0, 2); transaction2.commit(); try { transaction1.commit(); fail(); } catch (final ConflictingVersionException e) { - assertEquals( - "Optimistic lock failed. Expected parent version 2, was 0", - e.getMessage()); + assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage()); } } @Test public void testOptimisticLock_ConfigRegistry() throws Exception { - ConfigTransactionJMXClient transaction1 = configRegistryClient - .createTransaction(); - ConfigTransactionJMXClient transaction2 = configRegistryClient - .createTransaction(); + ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction(); + ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction(); transaction2.assertVersion(0, 2); transaction2.commit(); try { configRegistryClient.commitConfig(transaction1.getObjectName()); fail(); } catch (final ConflictingVersionException e) { - assertEquals( - "Optimistic lock failed. Expected parent version 2, was 0", - e.getMessage()); + assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage()); } } - @Test public void testQNames() { Set availableModuleFactoryQNames = configRegistryClient.getAvailableModuleFactoryQNames(); @@ -380,5 +339,4 @@ public class SimpleConfigurationTest extends AbstractConfigTest { assertEquals(Sets.newHashSet(expected), availableModuleFactoryQNames); } - } -- 2.36.6