Fix checkstyle issues to enforce it.
Change-Id: I306255919cdfe43208d7c254f2f6455f4126b92f
Signed-off-by: David Suarez <david.suarez.fuentes@gmail.com>
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>guava</artifactId>
</dependency>
- <!--Dependencies regardign RuntimeGeneratedMappingService-->
+ <!--Dependencies regarding RuntimeGeneratedMappingService-->
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-generator-impl</artifactId>
<build>
<plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<instructions>
<Bundle-Activator>org.opendaylight.controller.config.manager.impl.osgi.ConfigManagerActivator</Bundle-Activator>
<Private-Package>org.opendaylight.controller.config.manager.*,
- javax.annotation.*,</Private-Package>
+ javax.annotation.*,</Private-Package>
<Export-Package></Export-Package>
</instructions>
</configuration>
/*
- * 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,
public CommitInfo(final List<DestroyedModule> destroyedFromPreviousTransactions,
final Map<ModuleIdentifier, ModuleInternalTransactionalInfo> commitMap) {
- this.destroyedFromPreviousTransactions = Collections
- .unmodifiableList(destroyedFromPreviousTransactions);
+ this.destroyedFromPreviousTransactions = Collections.unmodifiableList(destroyedFromPreviousTransactions);
this.commitMap = Collections.unmodifiableMap(commitMap);
}
/**
- * Get ordered list of modules that can be closed in the same order, i.e.
- * first element will be a leaf on which no other module depends, n-th
- * element can only have dependencies with index smaller than n.
+ * Get ordered list of modules that can be closed in the same order, i.e. first
+ * element will be a leaf on which no other module depends, n-th element can
+ * only have dependencies with index smaller than n.
+ *
+ * @return list of destroyed modules
*/
public List<DestroyedModule> getDestroyedFromPreviousTransactions() {
return destroyedFromPreviousTransactions;
/*
- * 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,
*/
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;
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;
private volatile long versionCounter = 0;
/**
- * Contains current configuration in form of {moduleName:{instanceName,read
- * only module}} for copying state to new transaction. Each running module
- * is present just once, no matter how many interfaces it exposes.
+ * Contains current configuration in form of {moduleName:{instanceName,read only
+ * module}} for copying state to new transaction. Each running module is present
+ * just once, no matter how many interfaces it exposes.
*/
private final ConfigHolder currentConfig = new ConfigHolder();
/**
* Will return true unless there was a transaction that succeeded during
- * validation but failed in second phase of commit. In this case the server
- * is unstable and its state is undefined.
+ * validation but failed in second phase of commit. In this case the server is
+ * unstable and its state is undefined.
*/
private volatile boolean isHealthy = true;
/**
- * Holds Map<transactionName, transactionController> and purges it each time
- * its content is requested.
+ * Holds the map of transactions and purges it each time its content is
+ * requested.
*/
private final TransactionsHolder transactionsHolder = new TransactionsHolder();
// 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;
}
/**
- * Create new {@link ConfigTransactionControllerImpl }
+ * Create new {@link ConfigTransactionControllerImpl }.
*/
@Override
public ObjectName beginConfig() {
}
/**
- * @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;
versionCounter++;
final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
- TransactionJMXRegistratorFactory factory =
- () -> baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
+ TransactionJMXRegistratorFactory factory = () -> baseJMXRegistrator
+ .createTransactionJMXRegistrator(transactionName);
Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
resolver.getAllFactories());
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) {
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());
}
@GuardedBy("configTransactionLock")
private CommitStatus commitConfigSafe(final ObjectName transactionControllerON)
throws ConflictingVersionException, ValidationException {
- final String transactionName = ObjectNameUtil
- .getTransactionName(transactionControllerON);
- LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
+ final String transactionName = ObjectNameUtil.getTransactionName(transactionControllerON);
+ LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version,
+ versionCounter);
// find ConfigTransactionController
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder.getCurrentTransactions();
- Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry = transactions.get(transactionName);
+ Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+ transactionsHolder.getCurrentTransactions();
+ Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry =
+ transactions.get(transactionName);
if (configTransactionControllerEntry == null) {
- throw new IllegalArgumentException(String.format(
- "Transaction with name '%s' not found", transactionName));
+ throw new IllegalArgumentException(String.format("Transaction with name '%s' not found", transactionName));
}
ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
// check optimistic lock
if (version != configTransactionController.getParentVersion()) {
throw new ConflictingVersionException(
- String.format(
- "Optimistic lock failed. Expected parent version %d, was %d",
- version,
+ String.format("Optimistic lock failed. Expected parent version %d, was %d", version,
configTransactionController.getParentVersion()));
}
// optimistic lock ok
CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
- lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
- // non recoverable from here:
- try {
- return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
- // some libs throw Errors: e.g.
- // javax.xml.ws.spi.FactoryFinder$ConfigurationError
- } catch (final Throwable t) {
- isHealthy = false;
- LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
- throw Throwables.propagate(t);
- }
+ lastListOfFactories = Collections
+ .unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
+ return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
}
@GuardedBy("configTransactionLock")
private CommitStatus secondPhaseCommit(final ConfigTransactionControllerInternal configTransactionController,
- final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
+ final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
// close instances which were destroyed by the user, including
// (hopefully) runtime beans
- for (DestroyedModule toBeDestroyed : commitInfo
- .getDestroyedFromPreviousTransactions()) {
+ for (DestroyedModule toBeDestroyed : commitInfo.getDestroyedFromPreviousTransactions()) {
// closes instance (which should close
// runtime jmx registrator),
// also closes osgi registration and ModuleJMXRegistrator
// set RuntimeBeanRegistrators on beans implementing
// RuntimeBeanRegistratorAwareModule
Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
- for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
- .values()) {
+ for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted().values()) {
// set runtime jmx registrator if required
Module module = entry.getProxiedModule();
RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
if (module instanceof RuntimeBeanRegistratorAwareModule) {
- if(entry.hasOldModule()) {
+ if (entry.hasOldModule()) {
- if(module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
+ if (module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
} else {
}
}
// save it to info so it is accessible afterwards
- if(runtimeBeanRegistrator != null) {
+ if (runtimeBeanRegistrator != null) {
runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
}
}
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
// 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();
// 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:
}
Module realModule = entry.getRealModule();
- DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
- realModule, instance, moduleIdentifier,
- registryMBeanServer, configMBeanServer);
+ DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(realModule, instance,
+ moduleIdentifier, registryMBeanServer, configMBeanServer);
// register to JMX
try {
newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
} catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON,e);
+ throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON, e);
}
// register services to OSGi
- Map<ServiceInterfaceAnnotation, String /* service ref name */> annotationMapping = configTransactionController.getWritableRegistry().findServiceInterfaces(moduleIdentifier);
- BundleContext bc = configTransactionController.getModuleFactoryBundleContext(
- entry.getModuleFactory().getImplementationName());
+ Map<ServiceInterfaceAnnotation, String> annotationMapping = configTransactionController
+ .getWritableRegistry().findServiceInterfaces(moduleIdentifier);
+ BundleContext bc = configTransactionController
+ .getModuleFactoryBundleContext(entry.getModuleFactory().getImplementationName());
if (osgiRegistration == null) {
- osgiRegistration = beanToOsgiServiceManager.registerToOsgi(
- newReadableConfigBean.getInstance(), moduleIdentifier, bc, annotationMapping);
+ osgiRegistration = beanToOsgiServiceManager.registerToOsgi(newReadableConfigBean.getInstance(),
+ moduleIdentifier, bc, annotationMapping);
} else {
osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
}
- RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
- .get(entry.getIdentifier());
- ModuleInternalInfo newInfo = new ModuleInternalInfo(
- entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
- runtimeBeanRegistrator, newModuleJMXRegistrator,
- orderingIdx, entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
+ RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators.get(entry.getIdentifier());
+ ModuleInternalInfo newInfo = new ModuleInternalInfo(entry.getIdentifier(), newReadableConfigBean,
+ osgiRegistration, runtimeBeanRegistrator, newModuleJMXRegistrator, orderingIdx,
+ entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
newConfigEntries.put(realModule, newInfo);
orderingIdx++;
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);
}
/**
*/
@Override
public List<ObjectName> getOpenConfigs() {
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
- .getCurrentTransactions();
+ Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+ transactionsHolder.getCurrentTransactions();
List<ObjectName> result = new ArrayList<>(transactions.size());
- for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
- .values()) {
+ for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
+ configTransactionControllerEntry : transactions.values()) {
result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
}
return result;
}
/**
- * Abort open transactions and unregister read only modules. Since this
- * class is not responsible for registering itself under
- * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
- * here.
+ * Abort open transactions and unregister read only modules. Since this class is
+ * not responsible for registering itself under
+ * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it
+ * will not unregister itself here.
*/
@Override
public void close() {
- if(!closed.compareAndSet(false, true)) {
+ if (!closed.compareAndSet(false, true)) {
return;
}
// abort transactions
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
- .getCurrentTransactions();
- for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
- .values()) {
-
+ Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
+ transactionsHolder.getCurrentTransactions();
+ for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
+ configTransactionControllerEntry : transactions.values()) {
ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
- try {
- configTransactionControllerEntry.getValue().close();
- configTransactionController.abortConfig();
- } catch (final RuntimeException e) {
- LOG.debug("Ignoring exception while aborting {}", configTransactionController, e);
- }
+ configTransactionControllerEntry.getValue().close();
+ configTransactionController.abortConfig();
}
- // destroy all live objects one after another in order of the dependency hierarchy, from top to bottom
+ // destroy all live objects one after another in order of the dependency
+ // hierarchy, from top to bottom
List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
*/
@Override
public Set<String> getAvailableModuleNames() {
- return new HierarchicalConfigMBeanFactoriesHolder(
- resolver.getAllFactories()).getModuleNames();
+ return new HierarchicalConfigMBeanFactoriesHolder(resolver.getAllFactories()).getModuleNames();
}
/**
* {@inheritDoc}
*/
@Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
+ public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+ ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName);
+ return baseJMXRegistrator.queryNames(namePattern, null);
}
/**
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
- instanceName);
- return baseJMXRegistrator.queryNames(namePattern, null);
+ public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+ throws InstanceNotFoundException {
+ return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
}
/**
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
- final String instanceName) {
+ public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
String finalModuleName = moduleName == null ? "*" : moduleName;
String finalInstanceName = instanceName == null ? "*" : instanceName;
- ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
- finalModuleName, finalInstanceName);
+ ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
return baseJMXRegistrator.queryNames(namePattern, null);
}
ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
String transactionName = ObjectNameUtil.getTransactionName(objectName);
if (transactionName != null) {
- throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
+ throw new IllegalArgumentException(
+ "Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
}
// make sure exactly one match is found:
- LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
+ LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName),
+ ObjectNameUtil.getInstanceName(objectName));
}
// service reference functionality:
@Override
public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
}
}
@Override
public Map<String, Map<String, ObjectName>> getServiceMapping() {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.getServiceMapping();
}
}
@Override
public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
}
}
@Override
public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.lookupServiceInterfaceNames(objectName);
}
}
@Override
public String getServiceInterfaceName(final String namespace, final String localName) {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.getServiceInterfaceName(namespace, localName);
}
}
@Override
public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- synchronized(readableSRRegistryLock) {
+ synchronized (readableSRRegistryLock) {
readableSRRegistry.checkServiceReferenceExists(objectName);
}
}
@Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
- synchronized(readableSRRegistryLock) {
+ public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
+ throws InstanceNotFoundException {
+ synchronized (readableSRRegistryLock) {
return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
}
}
@Override
public String toString() {
- return "ConfigRegistryImpl{" +
- "versionCounter=" + versionCounter +
- ", version=" + version +
- '}';
+ return "ConfigRegistryImpl{" + "versionCounter=" + versionCounter + ", version=" + version + '}';
}
-}
-
-/**
- * Holds currently running modules
- */
-class ConfigHolder {
- private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
/**
- * Add all modules to the internal map. Also add service instance to OSGi
- * Service Registry.
+ * Inner class holding transactions and purges it each time its content is
+ * requested.
*/
- public void addAll(final Collection<ModuleInternalInfo> configInfos) {
- if (!currentConfig.isEmpty()) {
- throw new IllegalStateException(
- "Error - some config entries were not removed: "
- + currentConfig);
- }
- for (ModuleInternalInfo configInfo : configInfos) {
- add(configInfo);
+ class TransactionsHolder {
+ /**
+ * This map keeps transaction names and
+ * {@link ConfigTransactionControllerInternal} instances, because platform
+ * MBeanServer transforms mbeans into another representation. Map is cleaned
+ * every time current transactions are requested.
+ */
+ private final ConcurrentMap<String /* transactionName */,
+ Entry<ConfigTransactionControllerInternal,
+ ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
+
+ public void add(final String transactionName, final ConfigTransactionControllerInternal transactionController,
+ final ConfigTransactionLookupRegistry txLookupRegistry) {
+ Object oldValue = transactions.putIfAbsent(transactionName,
+ Maps.immutableEntry(transactionController, txLookupRegistry));
+ if (oldValue != null) {
+ throw new IllegalStateException("Error: two transactions with same name");
+ }
}
- }
- private void add(final ModuleInternalInfo configInfo) {
- ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
- if (oldValue != null) {
- throw new IllegalStateException(
- "Cannot overwrite module with same name:"
- + configInfo.getIdentifier() + ":" + configInfo);
+ /**
+ * Purges closed transactions from transactions map. Calling this method more
+ * than once within the method can modify the resulting map that was obtained in
+ * previous calls.
+ *
+ * @return current view on transactions map.
+ */
+ public Map<String, Entry<ConfigTransactionControllerInternal,
+ ConfigTransactionLookupRegistry>> getCurrentTransactions() {
+ // first, remove closed transaction
+ for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>>
+ it = transactions.entrySet().iterator(); it.hasNext();) {
+ Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
+ .next();
+ if (entry.getValue().getKey().isClosed()) {
+ it.remove();
+ }
+ }
+ return Collections.unmodifiableMap(transactions);
}
}
/**
- * Remove entry from current config.
+ * Inner class that holds currently running modules.
*/
- public void remove(final ModuleIdentifier name) {
- ModuleInternalInfo removed = currentConfig.remove(name);
- if (removed == null) {
- throw new IllegalStateException(
- "Cannot remove from ConfigHolder - name not found:" + name);
+ class ConfigHolder {
+ private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
+
+ /**
+ * Add all modules to the internal map. Also add service instance to OSGi
+ * Service Registry.
+ */
+ public void addAll(final Collection<ModuleInternalInfo> configInfos) {
+ if (!currentConfig.isEmpty()) {
+ throw new IllegalStateException("Error - some config entries were not removed: " + currentConfig);
+ }
+ for (ModuleInternalInfo configInfo : configInfos) {
+ add(configInfo);
+ }
}
- }
- public Collection<ModuleInternalInfo> getEntries() {
- return currentConfig.values();
- }
-
- public List<DestroyedModule> getModulesToBeDestroyed() {
- List<DestroyedModule> result = new ArrayList<>();
- for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
- result.add(moduleInternalInfo.toDestroyedModule());
+ private void add(final ModuleInternalInfo configInfo) {
+ ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
+ if (oldValue != null) {
+ throw new IllegalStateException(
+ "Cannot overwrite module with same name:" + configInfo.getIdentifier() + ":" + configInfo);
+ }
}
- Collections.sort(result);
- return result;
- }
-
-}
-
-/**
- * Holds Map<transactionName, transactionController> and purges it each time its
- * content is requested.
- */
-class TransactionsHolder {
- /**
- * This map keeps transaction names and
- * {@link ConfigTransactionControllerInternal} instances, because platform
- * MBeanServer transforms mbeans into another representation. Map is cleaned
- * every time current transactions are requested.
- */
- private final ConcurrentMap<String /* transactionName */,
- Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
+ /**
+ * Remove entry from current config.
+ */
+ public void remove(final ModuleIdentifier name) {
+ ModuleInternalInfo removed = currentConfig.remove(name);
+ if (removed == null) {
+ throw new IllegalStateException("Cannot remove from ConfigHolder - name not found:" + name);
+ }
+ }
- public void add(final String transactionName,
- final ConfigTransactionControllerInternal transactionController, final ConfigTransactionLookupRegistry txLookupRegistry) {
- Object oldValue = transactions.putIfAbsent(transactionName,
- Maps.immutableEntry(transactionController, txLookupRegistry));
- if (oldValue != null) {
- throw new IllegalStateException(
- "Error: two transactions with same name");
+ public Collection<ModuleInternalInfo> getEntries() {
+ return currentConfig.values();
}
- }
- /**
- * Purges closed transactions from transactions map. Calling this method more than once within the
- * method can modify the resulting map that was obtained in previous calls.
- *
- * @return current view on transactions map.
- */
- public Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> getCurrentTransactions() {
- // first, remove closed transaction
- for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>> it = transactions
- .entrySet().iterator(); it.hasNext(); ) {
- Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
- .next();
- if (entry.getValue().getKey().isClosed()) {
- it.remove();
+ public List<DestroyedModule> getModulesToBeDestroyed() {
+ List<DestroyedModule> result = new ArrayList<>();
+ for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
+ result.add(moduleInternalInfo.toDestroyedModule());
}
+ Collections.sort(result);
+ return result;
}
- return Collections.unmodifiableMap(transactions);
}
}
/*
- * 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,
*/
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();
/*
- * 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,
import org.slf4j.LoggerFactory;
/**
- * This is a JMX bean representing current transaction. It contains
- * transaction identifier, unique version and parent version for
- * optimistic locking.
+ * This is a JMX bean representing current transaction. It contains transaction
+ * identifier, unique version and parent version for optimistic locking.
*/
-class ConfigTransactionControllerImpl implements
- ConfigTransactionControllerInternal,
- ConfigTransactionControllerImplMXBean,
- Identifiable<TransactionIdentifier> {
+public class ConfigTransactionControllerImpl implements ConfigTransactionControllerInternal,
+ ConfigTransactionControllerImplMXBean, Identifiable<TransactionIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
private final ConfigTransactionLookupRegistry txLookupRegistry;
* 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;
private final SearchableServiceReferenceWritableRegistry writableSRRegistry;
public ConfigTransactionControllerImpl(final ConfigTransactionLookupRegistry txLookupRegistry,
- final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion,
- final Map<String, Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories,
- final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer,
- final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry writableSRRegistry) {
+ final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion,
+ final Map<String, Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories,
+ final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer,
+ final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry writableSRRegistry) {
this.txLookupRegistry = txLookupRegistry;
String transactionName = txLookupRegistry.getTransactionIdentifier().getName();
this.controllerON = ObjectNameUtil.createTransactionControllerON(transactionName);
}
@Override
- public void copyExistingModulesAndProcessFactoryDiff(final Collection<ModuleInternalInfo> existingModules, final List<ModuleFactory> lastListOfFactories) {
+ public void copyExistingModulesAndProcessFactoryDiff(final Collection<ModuleInternalInfo> existingModules,
+ final List<ModuleFactory> lastListOfFactories) {
// copy old configuration to this server
for (ModuleInternalInfo oldConfigInfo : existingModules) {
try {
Set<? extends Module> defaultModules = moduleFactory.getDefaultModules(dependencyResolverManager,
bundleContext);
for (Module module : defaultModules) {
- // ensure default module to be registered to jmx even if its module factory does not use dependencyResolverFactory
+ // ensure default module to be registered to jmx even if its module factory does
+ // not use dependencyResolverFactory
DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(module.getIdentifier());
final ObjectName objectName;
try {
} catch (final InstanceAlreadyExistsException e) {
throw new IllegalStateException(e);
}
-
// register default module as every possible service
- final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory);
+ final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
+ .getServiceInterfaceAnnotations(moduleFactory);
for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
try {
saveServiceReference(qname, module.getIdentifier().getInstanceName(), objectName);
} catch (final InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to register default module instance " + module + " as a service of " + qname, e);
+ throw new IllegalStateException(
+ "Unable to register default module instance " + module + " as a service of " + qname,
+ e);
}
}
}
List<ModuleIdentifier> modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory);
for (ModuleIdentifier name : modulesOfRemovedFactory) {
// remove service refs
- final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name).getModuleFactory();
- final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(moduleFactory);
+ final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name)
+ .getModuleFactory();
+ final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
+ .getServiceInterfaceAnnotations(moduleFactory);
for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
try {
removeServiceReference(qname, name.getInstanceName());
} catch (final InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to UNregister default module instance " + name + " as a service of " + qname, e);
+ throw new IllegalStateException(
+ "Unable to UNregister default module instance " + name + " as a service of " + qname,
+ e);
}
}
-
// close module
destroyModule(name);
}
}
}
-
+ @SuppressWarnings("IllegalCatch")
private synchronized void copyExistingModule(final ModuleInternalInfo oldConfigBeanInfo)
throws InstanceAlreadyExistsException {
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
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
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;
}
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
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;
}
}
+ @SuppressWarnings("IllegalCatch")
private void validateNoLocks() throws ValidationException {
transactionStatus.checkNotAborted();
LOG.trace("Validating transaction {}", getTransactionIdentifier());
// call validate()
List<ValidationException> collectedExceptions = new ArrayList<>();
- for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
- .getAllModules().entrySet()) {
+ for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager.getAllModules().entrySet()) {
ModuleIdentifier name = entry.getKey();
Module module = entry.getValue();
try {
module.validate();
} catch (final Exception e) {
- LOG.warn("Validation exception in {}", getTransactionName(),
- e);
- collectedExceptions.add(ValidationException
- .createForSingleException(name, e));
+ LOG.warn("Validation exception in {}", getTransactionName(), e);
+ collectedExceptions.add(ValidationException.createForSingleException(name, e));
}
}
if (!collectedExceptions.isEmpty()) {
- throw ValidationException
- .createFromCollectedValidationExceptions(collectedExceptions);
+ throw ValidationException.createFromCollectedValidationExceptions(collectedExceptions);
}
LOG.trace("Validated transaction {}", getTransactionIdentifier());
}
/**
* 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);
transactionStatus.checkCommitStarted();
if (!configBeanModificationDisabled.get()) {
throw new IllegalStateException(
- "Internal error - validateBeforeCommitAndLockTransaction should be called "
- + "to obtain a lock");
+ "Internal error - validateBeforeCommitAndLockTransaction should be called " + "to obtain a lock");
}
LOG.trace("Committing transaction {}", getTransactionIdentifier());
Map<ModuleIdentifier, Module> allModules = dependencyResolverManager.getAllModules();
- // call getInstance() on all Modules from top to bottom (from source to target of the dependency relation)
- // The source of a dependency closes itself and calls getInstance recursively on the dependencies (in case of reconfiguration)
- // This makes close() calls from top to bottom while createInstance() calls are performed bottom to top
- List<ModuleIdentifier> sortedModuleIdentifiers = Lists.reverse(dependencyResolverManager.getSortedModuleIdentifiers());
+ // call getInstance() on all Modules from top to bottom (from source to target
+ // of the dependency relation)
+ // The source of a dependency closes itself and calls getInstance recursively on
+ // the dependencies (in case of reconfiguration)
+ // This makes close() calls from top to bottom while createInstance() calls are
+ // performed bottom to top
+ List<ModuleIdentifier> sortedModuleIdentifiers = Lists
+ .reverse(dependencyResolverManager.getSortedModuleIdentifiers());
for (ModuleIdentifier moduleIdentifier : sortedModuleIdentifiers) {
Module module = allModules.get(moduleIdentifier);
- try {
- LOG.debug("About to commit {} in transaction {}",
- moduleIdentifier, getTransactionIdentifier());
- AutoCloseable instance = module.getInstance();
- Preconditions.checkNotNull(instance, "Instance is null:%s in transaction %s", moduleIdentifier, getTransactionIdentifier());
- } catch (Exception e) {
- LOG.error("Commit failed on {} in transaction {}", moduleIdentifier,
- getTransactionIdentifier(), e);
- internalAbort();
- throw new IllegalStateException(
- String.format("Error - getInstance() failed for %s in transaction %s",
- moduleIdentifier, getTransactionIdentifier()), e);
- }
+ LOG.debug("About to commit {} in transaction {}", moduleIdentifier, getTransactionIdentifier());
+ AutoCloseable instance = module.getInstance();
+ Preconditions.checkNotNull(instance, "Instance is null:%s in transaction %s", moduleIdentifier,
+ getTransactionIdentifier());
}
LOG.trace("Committed configuration {}", getTransactionIdentifier());
* {@inheritDoc}
*/
@Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return txLookupRegistry.lookupConfigBean(moduleName, instanceName);
+ public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+ return txLookupRegistry.lookupConfigBeans(moduleName, instanceName);
}
/**
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- return txLookupRegistry.lookupConfigBeans(moduleName, instanceName);
+ public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+ throws InstanceNotFoundException {
+ return txLookupRegistry.lookupConfigBean(moduleName, instanceName);
}
/**
txLookupRegistry.checkConfigBeanExists(objectName);
}
-
/**
* {@inheritDoc}
*/
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
- final String instanceName) {
+ public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
return txLookupRegistry.lookupRuntimeBeans(moduleName, instanceName);
}
@Override
public BundleContext getModuleFactoryBundleContext(final String factoryName) {
- Map.Entry<ModuleFactory, BundleContext> factoryBundleContextEntry = this.currentlyRegisteredFactories.get(factoryName);
+ Map.Entry<ModuleFactory, BundleContext> factoryBundleContextEntry = this.currentlyRegisteredFactories
+ .get(factoryName);
if (factoryBundleContextEntry == null || factoryBundleContextEntry.getValue() == null) {
throw new NullPointerException("Bundle context of " + factoryName + " ModuleFactory not found.");
}
// 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);
}
}
@Override
- public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
+ public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(
+ final String serviceInterfaceQName) {
return writableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
}
@Override
- public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
+ public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
+ throws InstanceNotFoundException {
return writableSRRegistry.lookupServiceInterfaceNames(objectName);
}
}
@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);
}
}
@Override
- public SearchableServiceReferenceWritableRegistry getWritableRegistry() {
+ public SearchableServiceReferenceWritableRegistry getWritableRegistry() {
return writableSRRegistry;
}
}
@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);
}
}
/*
- * 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,
/**
* 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();
-
}
/*
- * 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,
* Defines contract between {@link ConfigTransactionControllerImpl} (producer)
* and {@link ConfigRegistryImpl} (consumer).
*/
-interface ConfigTransactionControllerInternal extends
- ConfigTransactionControllerImplMXBean, AutoCloseable {
-
-
+interface ConfigTransactionControllerInternal extends ConfigTransactionControllerImplMXBean, AutoCloseable {
/**
- * 1, Copy already committed modules to current transaction.
- * 2, Diff: compute added and removed factories from last run, then create new modules using
- * {@link org.opendaylight.controller.config.spi.ModuleFactory#getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory, BundleContext)}
+ * 1, Copy already committed modules to current transaction. 2, Diff: compute
+ * added and removed factories from last run, then create new modules using
+ * {@link org.opendaylight.controller.config.spi
+ * .ModuleFactory#getDefaultModules(org.opendaylight.controller
+ * .config .api.DependencyResolverFactory, BundleContext)}
* and remove modules belonging to removed factories.
+ *
+ * @param entries
+ * entries
+ * @param lastListOfFactories
+ * list of factories
*/
- void copyExistingModulesAndProcessFactoryDiff(Collection<ModuleInternalInfo> entries, List<ModuleFactory> lastListOfFactories);
+ void copyExistingModulesAndProcessFactoryDiff(Collection<ModuleInternalInfo> entries,
+ List<ModuleFactory> lastListOfFactories);
/**
- * Call {@link org.opendaylight.controller.config.spi.Module#validate()} on
- * all beans in transaction. Lock transaction after successful validation.
- * This method can be called multiple times if validation fails, but cannot
- * be called after it did not throw exception.
+ * Call {@link org.opendaylight.controller.config.spi.Module#validate()} on all
+ * beans in transaction. Lock transaction after successful validation. This
+ * method can be called multiple times if validation fails, but cannot be called
+ * after it did not throw exception.
*
- * @throws {@link RuntimeException} if validation fails. It is safe to run
- * this method in future
- * @return CommitInfo
+ * @return CommitInfo commit info
*/
- CommitInfo validateBeforeCommitAndLockTransaction()
- throws ValidationException;
+ CommitInfo validateBeforeCommitAndLockTransaction() throws ValidationException;
/**
- * Call {@link org.opendaylight.controller.config.spi.Module#getInstance()}
- * on all beans in transaction. This method can be only called once.
+ * Call {@link org.opendaylight.controller.config.spi.Module#getInstance()} on
+ * all beans in transaction. This method can be only called once.
*
- * @throws {@link RuntimeException} commit fails, indicates bug in config
- * bean
- * @return ordered list of module identifiers that respects dependency
- * order.
+ * @return ordered list of module identifiers that respects dependency order
*/
List<ModuleIdentifier> secondPhaseCommit();
/**
- * @return ObjectName of this transaction controller
+ * Gets the objectName of this transaction controller.
+ *
+ * @return ObjectName
*/
ObjectName getControllerObjectName();
/**
- * @return true iif transaction was committed or aborted.
+ * Check if the transaction was committed or aborted.
+ *
+ * @return result of transaction
*/
boolean isClosed();
BundleContext getModuleFactoryBundleContext(String factoryName);
- SearchableServiceReferenceWritableRegistry getWritableRegistry();
+ SearchableServiceReferenceWritableRegistry getWritableRegistry();
TransactionIdentifier getTransactionIdentifier();
/*
- * 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,
import org.osgi.framework.BundleContext;
/**
- * Responsible for creating TransactionJMXRegistrator, registering transaction and all its beans,
- * lookup of beans, closing of TransactionJMXRegistrator.
+ * Responsible for creating TransactionJMXRegistrator, registering transaction
+ * and all its beans, lookup of beans, closing of TransactionJMXRegistrator.
*/
-class ConfigTransactionLookupRegistry implements LookupRegistry, Closeable {
+class ConfigTransactionLookupRegistry implements LookupRegistry, Closeable {
private final TransactionJMXRegistrator transactionJMXRegistrator;
private final TransactionIdentifier transactionIdentifier;
private final TransactionModuleJMXRegistrator txModuleJMXRegistrator;
private final Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories;
+ interface TransactionJMXRegistratorFactory {
+ TransactionJMXRegistrator create();
+ }
+
ConfigTransactionLookupRegistry(final TransactionIdentifier transactionIdentifier,
- final TransactionJMXRegistratorFactory factory, final Map<String, Entry<ModuleFactory, BundleContext>> allCurrentFactories) {
+ final TransactionJMXRegistratorFactory factory,
+ final Map<String, Entry<ModuleFactory, BundleContext>> allCurrentFactories) {
this.transactionIdentifier = transactionIdentifier;
this.transactionJMXRegistrator = factory.create();
this.txModuleJMXRegistrator = transactionJMXRegistrator.createTransactionModuleJMXRegistrator();
}
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);
}
}
* {@inheritDoc}
*/
@Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
+ public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+ ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName,
+ transactionIdentifier.getName());
+ return txModuleJMXRegistrator.queryNames(namePattern, null);
}
/**
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
- instanceName, transactionIdentifier.getName());
- return txModuleJMXRegistrator.queryNames(namePattern, null);
+ public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
+ throws InstanceNotFoundException {
+ return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
}
@Override
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() {
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);
}
* {@inheritDoc}
*/
@Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
- final String instanceName) {
+ public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
String finalModuleName = moduleName == null ? "*" : moduleName;
String finalInstanceName = instanceName == null ? "*" : instanceName;
- ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
- finalModuleName, finalInstanceName);
+ ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
return transactionJMXRegistrator.queryNames(namePattern, null);
}
@Override
public String toString() {
- return "ConfigTransactionLookupRegistry{" +
- "transactionIdentifier=" + transactionIdentifier +
- '}';
+ return "ConfigTransactionLookupRegistry{" + "transactionIdentifier=" + transactionIdentifier + '}';
}
}
-
-interface TransactionJMXRegistratorFactory {
- TransactionJMXRegistrator create();
-}
/*
- * 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,
ModuleIdentifierWithNanos old = new ModuleIdentifierWithNanos();
while (!this.isInterrupted()) {
ModuleIdentifierWithNanos copy;
- synchronized(this) {
+ synchronized (this) {
copy = new ModuleIdentifierWithNanos(DeadlockMonitor.this.top);
}
private final long nanoTime;
private ModuleIdentifierWithNanos() {
- this((ModuleIdentifier)null);
+ this((ModuleIdentifier) null);
}
private ModuleIdentifierWithNanos(final ModuleIdentifier moduleIdentifier) {
}
@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;
}
@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 + '}';
}
}
}
/*
- * 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,
/**
* Provides metadata about Module from controller to registry.
*/
-public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>,
- Identifiable<ModuleIdentifier>{
+public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>, Identifiable<ModuleIdentifier> {
private final ModuleIdentifier name;
// this registrator is passed to runtime bean registrator and config
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;
}
/**
+ * 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;
/**
* 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);
}
/*
- * 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,
public interface SearchableServiceReferenceWritableRegistry extends ServiceReferenceWritableRegistry {
/**
- * Return mapping between service ref names and service interface annotation for given
- * module.
+ * Return mapping between service ref names and service interface annotation for
+ * given module.
*
- * @throws java.lang.IllegalArgumentException if any of service qNames is not found
- * @throws java.lang.NullPointerException if parameter is null
+ * @param moduleIdentifier module id
+ * @return map
+ * @throws java.lang.IllegalArgumentException
+ * if any of service qNames is not found
+ * @throws java.lang.NullPointerException
+ * if parameter is null
*/
- Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(ModuleIdentifier moduleIdentifier);
-
+ Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
+ ModuleIdentifier moduleIdentifier);
}
/*
- * 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,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
+public class ServiceReferenceRegistryImpl
+ implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
private final Map<String, ModuleFactory> factories;
private final Map<String, Set<String>> factoryNamesToQNames;
- // validator of incoming ObjectNames - throws InstanceNotFoundException if not found either in registry or transaction
+ // validator of incoming ObjectNames - throws InstanceNotFoundException if not
+ // found either in registry or transaction
private final LookupRegistry lookupRegistry;
private final ServiceReferenceRegistrator serviceReferenceRegistrator;
// helper method for getting QName of SI from namespace + local name
- private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>> namespacesToAnnotations;
+ private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>>
+ namespacesToAnnotations;
private final Map<String /* service qName */, ServiceInterfaceAnnotation> serviceQNamesToAnnotations;
// all Service Interface qNames for sanity checking
private final Set<String /* qName */> allQNames;
- Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef = new HashMap<>();
-
+ Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef =
+ new HashMap<>();
// actual reference database
private final Map<ServiceReference, ModuleIdentifier> refNames = new HashMap<>();
private final boolean writable;
- private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> mBeans = new HashMap<>();
+ private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
+ managementBeans = new HashMap<>();
- private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories, final LookupRegistry lookupRegistry,
- final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, final boolean writable) {
+ private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories,
+ final LookupRegistry lookupRegistry,
+ final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory,
+ final boolean writable) {
this.factories = factories;
this.writable = writable;
this.lookupRegistry = lookupRegistry;
for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
if (!entry.getKey().equals(entry.getValue().getImplementationName())) {
LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
- throw new IllegalArgumentException("Possible error in code: Mismatch between supplied and actual name of " + entry);
+ throw new IllegalArgumentException(
+ "Possible error in code: Mismatch between supplied and actual name of " + entry);
}
- Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue());
- Set<String> qNames = InterfacesHelper.getQNames(siAnnotations);
+ Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper
+ .getServiceInterfaceAnnotations(entry.getValue());
+ Set<String> names = InterfacesHelper.getQNames(siAnnotations);
allAnnotations.addAll(siAnnotations);
- allQNameSet.addAll(qNames);
- modifiableFactoryNamesToQNames.put(entry.getKey(), qNames);
+ allQNameSet.addAll(names);
+ modifiableFactoryNamesToQNames.put(entry.getKey(), names);
}
this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames);
this.allQNames = ImmutableSet.copyOf(allQNameSet);
// fill namespacesToAnnotations
- Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> modifiableNamespacesToAnnotations = new HashMap<>();
- Map<String /* service qName*/, ServiceInterfaceAnnotation> modifiableServiceQNamesToAnnotations = new HashMap<>();
+ Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>>
+ modifiableNamespacesToAnnotations = new HashMap<>();
+ Map<String /* service qName */, ServiceInterfaceAnnotation>
+ modifiableServiceQNamesToAnnotations = new HashMap<>();
for (ServiceInterfaceAnnotation sia : allAnnotations) {
- Map<String, ServiceInterfaceAnnotation> ofNamespace =
- modifiableNamespacesToAnnotations.computeIfAbsent(sia.namespace(), k -> new HashMap<>());
+ Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations
+ .computeIfAbsent(sia.namespace(), k -> new HashMap<>());
if (ofNamespace.containsKey(sia.localName())) {
LOG.error(
- "Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
+ "Cannot construct namespacesToAnnotations map, conflict between local names in {},"
+ + " offending local name: {}, map so far {}",
sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
- throw new IllegalArgumentException("Conflict between local names in " + sia.namespace() + " : " + sia.localName());
+ throw new IllegalArgumentException(
+ "Conflict between local names in " + sia.namespace() + " : " + sia.localName());
}
ofNamespace.put(sia.localName(), sia);
modifiableServiceQNamesToAnnotations.put(sia.value(), sia);
}
/**
- * 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:
}
@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();
}
return "initial";
}
};
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = () -> new ServiceReferenceRegistrator() {
- @Override
- public String getNullableTransactionName() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object, final ObjectName on) throws InstanceAlreadyExistsException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void close() {
- }
- };
+ ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+ () -> new ServiceReferenceRegistrator() {
+ @Override
+ public String getNullableTransactionName() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object,
+ final ObjectName on) throws InstanceAlreadyExistsException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void close() {
+ }
+ };
return new ServiceReferenceRegistryImpl(Collections.<String, ModuleFactory>emptyMap(), lookupRegistry,
serviceReferenceRegistratorFactory, false);
}
- /**
- * Static constructor for transaction controller. Take current state as seen by config registry, allow writing new data.
- */
- public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(final ServiceReferenceReadableRegistry oldReadableRegistry,
- final ConfigTransactionLookupRegistry txLookupRegistry,
- final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
+ public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(
+ final ServiceReferenceReadableRegistry oldReadableRegistry,
+ final ConfigTransactionLookupRegistry txLookupRegistry,
+ final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
if (txLookupRegistry == null) {
throw new IllegalArgumentException("txLookupRegistry is null");
}
ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry;
Map<String, ModuleFactory> factories = extractFactoriesMap(currentlyRegisteredFactories);
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(
- txLookupRegistry.getTxModuleJMXRegistrator(), txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
+ ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+ new ServiceReferenceTransactionRegistratorFactoryImpl(txLookupRegistry.getTxModuleJMXRegistrator(),
+ txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(factories, txLookupRegistry,
serviceReferenceRegistratorFactory, true);
copy(old, newRegistry, txLookupRegistry.getTransactionIdentifier().getName());
/**
* Copy back state to config registry after commit.
+ *
+ * @param oldWritableRegistry
+ * old registry
+ * @param lookupRegistry
+ * lookup registry
+ * @param baseJMXRegistrator
+ * JMX registrator
+ * @return service reference
*/
- public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(final ServiceReferenceWritableRegistry oldWritableRegistry,
- final LookupRegistry lookupRegistry, final BaseJMXRegistrator baseJMXRegistrator) {
+ public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(
+ final ServiceReferenceWritableRegistry oldWritableRegistry, final LookupRegistry lookupRegistry,
+ final BaseJMXRegistrator baseJMXRegistrator) {
ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldWritableRegistry;
- // even if factories do change, nothing in the mapping can change between transactions
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
+ // even if factories do change, nothing in the mapping can change between
+ // transactions
+ ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
+ new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(old.factories, lookupRegistry,
serviceReferenceRegistratorFactory, false);
copy(old, newRegistry, null);
return newRegistry;
}
- /**
- * Fill refNames and mBeans maps from old instance
- */
- private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry, final String nullableDstTransactionName) {
- for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> refNameEntry : old.mBeans.entrySet()) {
+ private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry,
+ final String nullableDstTransactionName) {
+ for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
+ refNameEntry : old.managementBeans.entrySet()) {
ObjectName currentImplementation;
ObjectName currentImplementationSrc = refNameEntry.getValue().getKey().getCurrentImplementation();
if (nullableDstTransactionName != null) {
- currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc, nullableDstTransactionName);
+ currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc,
+ nullableDstTransactionName);
} else {
currentImplementation = ObjectNameUtil.withoutTransactionName(currentImplementationSrc);
}
}
}
- private static Map<String, ModuleFactory> extractFactoriesMap(final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
+ private static Map<String, ModuleFactory> extractFactoriesMap(
+ final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
Map<String, ModuleFactory> result = new HashMap<>();
for (Entry<String, Entry<ModuleFactory, BundleContext>> entry : currentlyRegisteredFactories.entrySet()) {
result.put(entry.getKey(), entry.getValue().getKey());
}
@Override
- public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(final ModuleIdentifier moduleIdentifier) {
- Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef.get(moduleIdentifier);
+ public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
+ final ModuleIdentifier moduleIdentifier) {
+ Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef
+ .get(moduleIdentifier);
if (result == null) {
return Collections.emptyMap();
}
}
@Override
- public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
+ public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
+ throws InstanceNotFoundException {
lookupRegistry.checkConfigBeanExists(objectName);
String factoryName = ObjectNameUtil.getFactoryName(objectName);
// reading:
@Override
- public synchronized Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> getServiceMapping() {
+ public synchronized Map<String, Map<String/* refName */, ObjectName>> getServiceMapping() {
Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> result = new HashMap<>();
- for (Entry<ServiceReference, ModuleIdentifier> entry: refNames.entrySet()) {
- String qName = entry.getKey().getServiceInterfaceQName();
- Map<String /* refName */, ObjectName> innerMap = result.computeIfAbsent(qName, k -> new HashMap<>());
+ for (Entry<ServiceReference, ModuleIdentifier> entry : refNames.entrySet()) {
+ String name = entry.getKey().getServiceInterfaceQName();
+ Map<String /* refName */, ObjectName> innerMap = result.computeIfAbsent(name, k -> new HashMap<>());
innerMap.put(entry.getKey().getRefName(), getObjectName(entry.getValue()));
}
return result;
}
@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) {
}
@Override
- public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
+ public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(
+ final String serviceInterfaceQName) {
Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
if (innerMap == null) {
}
@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);
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);
}
@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) {
if (serviceInterfaceQNames == null) {
LOG.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
factoryNamesToQNames, moduleIdentifier);
- throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + moduleIdentifier.getFactoryName());
+ throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory "
+ + moduleIdentifier.getFactoryName());
}
// supplied serviceInterfaceName must exist in this collection
if (!serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName())) {
- LOG.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
- throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory " + moduleIdentifier.getFactoryName());
+ LOG.error("Cannot find qName {} with factory name {}, found {}",
+ serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(),
+ serviceInterfaceQNames);
+ throw new IllegalArgumentException(
+ "Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory "
+ + moduleIdentifier.getFactoryName());
}
-
// create service reference object name, put to mBeans
ObjectName result = getServiceON(serviceReference);
- Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry = mBeans.get(serviceReference);
+ Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry =
+ managementBeans.get(serviceReference);
if (mxBeanEntry == null) {
// create dummy mx bean
ServiceReferenceMXBeanImpl dummyMXBean = new ServiceReferenceMXBeanImpl(moduleON);
} catch (final InstanceAlreadyExistsException e) {
throw new IllegalStateException("Possible error in code. Cannot register " + result, e);
}
- mBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
+ managementBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
} else {
// update
mxBeanEntry.getKey().setCurrentImplementation(moduleON);
}
// save to refNames
refNames.put(serviceReference, moduleIdentifier);
- Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations =
- modulesToServiceRef.computeIfAbsent(moduleIdentifier, k -> new HashMap<>());
+ Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations = modulesToServiceRef
+ .computeIfAbsent(moduleIdentifier, k -> new HashMap<>());
- ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations.get(serviceReference.getServiceInterfaceQName());
- Preconditions.checkNotNull(annotation, "Possible error in code, cannot find annotation for " + serviceReference);
+ ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations
+ .get(serviceReference.getServiceInterfaceQName());
+ Preconditions.checkNotNull(annotation,
+ "Possible error in code, cannot find annotation for " + serviceReference);
refNamesToAnnotations.put(annotation, serviceReference.getRefName());
return result;
}
serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
}
- return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
+ return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(),
+ serviceReference.getRefName());
}
@Override
- public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException{
+ public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName)
+ throws InstanceNotFoundException {
ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
removeServiceReference(serviceReference);
}
- private synchronized void removeServiceReference(final ServiceReference serviceReference) throws InstanceNotFoundException {
+ private synchronized void removeServiceReference(final ServiceReference serviceReference)
+ throws InstanceNotFoundException {
LOG.debug("Removing service reference {} from {}", serviceReference, this);
assertWritable();
// is the qName known?
if (!allQNames.contains(serviceReference.getServiceInterfaceQName())) {
LOG.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
- throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName());
+ throw new IllegalArgumentException(
+ "Cannot find service interface " + serviceReference.getServiceInterfaceQName());
}
ModuleIdentifier removed = refNames.remove(serviceReference);
- if (removed == null){
+ if (removed == null) {
throw new InstanceNotFoundException("Cannot find " + serviceReference.getServiceInterfaceQName());
}
- Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry = mBeans.remove(serviceReference);
+ Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry =
+ managementBeans.remove(serviceReference);
if (entry == null) {
throw new IllegalStateException("Possible code error: cannot remove from mBeans: " + serviceReference);
}
@Override
public synchronized void removeAllServiceReferences() {
assertWritable();
- for (ServiceReference serviceReference: mBeans.keySet()) {
+ for (ServiceReference serviceReference : managementBeans.keySet()) {
try {
removeServiceReference(serviceReference);
} catch (final InstanceNotFoundException e) {
}
@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
return removeServiceReferences(moduleObjectName, serviceInterfaceQNames);
}
-
- private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> qNames) throws InstanceNotFoundException {
+ private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> names)
+ throws InstanceNotFoundException {
ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE);
assertWritable();
- Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, qNames);
+ Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names);
for (ServiceReference sr : serviceReferencesLinkingTo) {
removeServiceReference(sr);
}
return !serviceReferencesLinkingTo.isEmpty();
}
- private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set<String> serviceInterfaceQNames) {
+ private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName,
+ final Set<String> serviceInterfaceQNames) {
String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
if (serviceInterfaceQNames == null) {
- LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
- throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + factoryName);
+ LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName,
+ factoryNamesToQNames, moduleObjectName);
+ throw new IllegalStateException(
+ "Possible error in code: cannot find annotations of existing factory " + factoryName);
}
String instanceName = ObjectNameUtil.getInstanceName(moduleObjectName);
ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
@Override
public String toString() {
- return "ServiceReferenceRegistryImpl{" +
- "lookupRegistry=" + lookupRegistry +
- "refNames=" + refNames +
- ", factoryNamesToQNames=" + factoryNamesToQNames +
- '}';
+ return "ServiceReferenceRegistryImpl{" + "lookupRegistry=" + lookupRegistry + "refNames=" + refNames
+ + ", factoryNamesToQNames=" + factoryNamesToQNames + '}';
}
@Override
/*
- * 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,
}
@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;
/*
- * 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,
* by creating proxy that would throw exception if those methods are called
* during validation. Tracks dependencies for ordering purposes.
*/
-final class DependencyResolverImpl implements DependencyResolver,
- Comparable<DependencyResolverImpl> {
+public final class DependencyResolverImpl implements DependencyResolver, Comparable<DependencyResolverImpl> {
private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
private final ModulesHolder modulesHolder;
private final ServiceReferenceReadableRegistry readableRegistry;
private final BindingContextProvider bindingContextProvider;
private final String transactionName;
- private final MBeanServer mBeanServer;
+ private final MBeanServer beanServer;
private Integer maxDependencyDepth;
- DependencyResolverImpl(final ModuleIdentifier currentModule,
- final TransactionStatus transactionStatus, final ModulesHolder modulesHolder,
- final ServiceReferenceReadableRegistry readableRegistry, final BindingContextProvider bindingContextProvider,
- final String transactionName, final MBeanServer mBeanServer) {
+ public DependencyResolverImpl(final ModuleIdentifier currentModule, final TransactionStatus transactionStatus,
+ final ModulesHolder modulesHolder, final ServiceReferenceReadableRegistry readableRegistry,
+ final BindingContextProvider bindingContextProvider, final String transactionName,
+ final MBeanServer beanServer) {
this.bindingContextProvider = bindingContextProvider;
this.name = currentModule;
this.transactionStatus = transactionStatus;
this.modulesHolder = modulesHolder;
this.readableRegistry = readableRegistry;
this.transactionName = transactionName;
- this.mBeanServer = mBeanServer;
+ this.beanServer = beanServer;
}
/**
* {@inheritDoc}
*/
- //TODO: check for cycles
+ // TODO: check for cycles
@Override
- public void validateDependency(
- final Class<? extends AbstractServiceInterface> expectedServiceInterface,
+ public void validateDependency(final Class<? extends AbstractServiceInterface> expectedServiceInterface,
final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
this.transactionStatus.checkNotCommitted();
if (expectedServiceInterface == null) {
- throw new NullPointerException(
- "Parameter 'expectedServiceInterface' is null");
+ throw new NullPointerException("Parameter 'expectedServiceInterface' is null");
}
if (jmxAttribute == null) {
throw new NullPointerException("Parameter 'jmxAttribute' is null");
}
JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
- "is null, expected dependency implementing "
- + expectedServiceInterface, jmxAttribute
- );
-
+ "is null, expected dependency implementing " + expectedServiceInterface, jmxAttribute);
// check that objectName belongs to this transaction - this should be
// stripped
// in DynamicWritableWrapper
- final boolean hasTransaction = ObjectNameUtil
- .getTransactionName(dependentReadOnlyON) != null;
- JmxAttributeValidationException.checkCondition(
- !hasTransaction,
- String.format("ObjectName should not contain "
- + "transaction name. %s set to %s. ", jmxAttribute,
- dependentReadOnlyON
- ), jmxAttribute
- );
+ final boolean hasTransaction = ObjectNameUtil.getTransactionName(dependentReadOnlyON) != null;
+ JmxAttributeValidationException.checkCondition(!hasTransaction,
+ String.format("ObjectName should not contain " + "transaction name. %s set to %s. ", jmxAttribute,
+ dependentReadOnlyON),
+ jmxAttribute);
final ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
- final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON, ObjectNameUtil
- .TYPE_MODULE);
+ final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON,
+ ObjectNameUtil.TYPE_MODULE);
final ModuleFactory foundFactory = this.modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
- final boolean implementsSI = foundFactory
- .isModuleImplementingServiceInterface(expectedServiceInterface);
+ final boolean implementsSI = foundFactory.isModuleImplementingServiceInterface(expectedServiceInterface);
if (!implementsSI) {
final String message = String.format(
"Found module factory does not expose expected service interface. "
+ "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
+ "attribute %s",
- foundFactory.getImplementationName(), foundFactory,
- expectedServiceInterface, newDependentReadOnlyON,
- jmxAttribute
- );
+ foundFactory.getImplementationName(), foundFactory, expectedServiceInterface,
+ newDependentReadOnlyON, jmxAttribute);
throw new JmxAttributeValidationException(message, jmxAttribute);
}
synchronized (this) {
if (ObjectNameUtil.isServiceReference(translatedDependentReadOnlyON)) {
final String serviceQName = ObjectNameUtil.getServiceQName(translatedDependentReadOnlyON);
final String refName = ObjectNameUtil.getReferenceName(translatedDependentReadOnlyON);
- translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
+ // strip again of transaction name
+ translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName(
this.readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
}
return translatedDependentReadOnlyON;
}
- //TODO: check for cycles
+ // TODO: check for cycles
@Override
public <T> T resolveInstance(final Class<T> expectedType, final ObjectName dependentReadOnlyON,
- final JmxAttribute jmxAttribute) {
+ final JmxAttribute jmxAttribute) {
final Module module = resolveModuleInstance(dependentReadOnlyON, jmxAttribute);
synchronized (this) {
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));
}
.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;
public <T extends BaseIdentity> Class<? extends T> resolveIdentity(final IdentityAttributeRef identityRef,
final Class<T> expectedBaseClass) {
final QName qName = QName.create(identityRef.getqNameOfIdentity());
- final Class<?> deserialized = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
+ final Class<?> deserialized = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
if (deserialized == null) {
throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
+ this.bindingContextProvider.getBindingContext());
return (Class<T>) deserialized;
}
LOG.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.", identityRef,
- deserialized, expectedBaseClass);
- throw new IllegalArgumentException("Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
+ deserialized, expectedBaseClass);
+ throw new IllegalArgumentException(
+ "Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
}
@Override
public <T extends BaseIdentity> void validateIdentity(final IdentityAttributeRef identityRef,
final Class<T> expectedBaseClass, final JmxAttribute jmxAttribute) {
- try {
- resolveIdentity(identityRef, expectedBaseClass);
- } catch (final Exception e) {
- throw JmxAttributeValidationException.wrap(e, jmxAttribute);
- }
+ resolveIdentity(identityRef, expectedBaseClass);
}
@Override
- public int compareTo(final DependencyResolverImpl o) {
+ public int compareTo(final DependencyResolverImpl dependencyResolverImpl) {
this.transactionStatus.checkCommitStarted();
- return Integer.compare(getMaxDependencyDepth(),
- o.getMaxDependencyDepth());
+ return Integer.compare(getMaxDependencyDepth(), dependencyResolverImpl.getMaxDependencyDepth());
}
int getMaxDependencyDepth() {
void countMaxDependencyDepth(final DependencyResolverManager manager) {
// We can calculate the dependency after second phase commit was started
- // Second phase commit starts after validation and validation adds the dependencies into the dependency resolver, which are necessary for the calculation
- // FIXME generated code for abstract module declares validate method as non-final
- // Overriding the validate would cause recreate every time instead of reuse + also possibly wrong close order if there is another module depending
+ // Second phase commit starts after validation and validation adds the
+ // dependencies into the dependency resolver, which are necessary for the
+ // calculation
+ // FIXME generated code for abstract module declares validate method as
+ // non-final
+ // Overriding the validate would cause recreate every time instead of reuse +
+ // also possibly wrong close order if there is another module depending
this.transactionStatus.checkCommitStarted();
if (this.maxDependencyDepth == null) {
- this.maxDependencyDepth = getMaxDepth(this, manager,
- new LinkedHashSet<>());
+ this.maxDependencyDepth = getMaxDepth(this, manager, new LinkedHashSet<>());
}
}
- private static int getMaxDepth(final DependencyResolverImpl impl,
- final DependencyResolverManager manager,
- final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
+ private static int getMaxDepth(final DependencyResolverImpl impl, final DependencyResolverManager manager,
+ final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
int maxDepth = 0;
- final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(
- chainForDetectingCycles);
+ final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(chainForDetectingCycles);
chainForDetectingCycles2.add(impl.getIdentifier());
for (final ModuleIdentifier dependencyName : impl.dependencies) {
- final DependencyResolverImpl dependentDRI = manager
- .getOrCreate(dependencyName);
+ final DependencyResolverImpl dependentDRI = manager.getOrCreate(dependencyName);
if (chainForDetectingCycles2.contains(dependencyName)) {
- throw new IllegalStateException(String.format(
- "Cycle detected, %s contains %s",
- chainForDetectingCycles2, dependencyName));
+ throw new IllegalStateException(
+ String.format("Cycle detected, %s contains %s", chainForDetectingCycles2, dependencyName));
}
int subDepth;
if (dependentDRI.maxDependencyDepth != null) {
subDepth = dependentDRI.maxDependencyDepth;
} else {
- subDepth = getMaxDepth(dependentDRI, manager,
- chainForDetectingCycles2);
+ subDepth = getMaxDepth(dependentDRI, manager, chainForDetectingCycles2);
dependentDRI.maxDependencyDepth = subDepth;
}
if (subDepth + 1 > maxDepth) {
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
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);
}
}
/*
- * 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,
*/
public class DependencyResolverManager implements DependencyResolverFactory, AutoCloseable {
@GuardedBy("this")
- private final Map<ModuleIdentifier, DependencyResolverImpl> moduleIdentifiersToDependencyResolverMap = new HashMap<>();
+ private final Map<ModuleIdentifier, DependencyResolverImpl>
+ moduleIdentifiersToDependencyResolverMap = new HashMap<>();
private final TransactionIdentifier transactionIdentifier;
private final ModulesHolder modulesHolder;
private final TransactionStatus transactionStatus;
private final ServiceReferenceReadableRegistry readableRegistry;
private final BindingContextProvider bindingContextProvider;
private final DeadlockMonitor deadlockMonitor;
- private final MBeanServer mBeanServer;
+ private final MBeanServer beanServer;
public DependencyResolverManager(final TransactionIdentifier transactionIdentifier,
- final TransactionStatus transactionStatus,
- final ServiceReferenceReadableRegistry readableRegistry, final BindingContextProvider bindingContextProvider,
- final MBeanServer mBeanServer) {
+ final TransactionStatus transactionStatus, final ServiceReferenceReadableRegistry readableRegistry,
+ final BindingContextProvider bindingContextProvider, final MBeanServer beanServer) {
this.transactionIdentifier = transactionIdentifier;
this.modulesHolder = new ModulesHolder(transactionIdentifier);
this.transactionStatus = transactionStatus;
this.readableRegistry = readableRegistry;
this.bindingContextProvider = bindingContextProvider;
this.deadlockMonitor = new DeadlockMonitor(transactionIdentifier);
- this.mBeanServer = mBeanServer;
+ this.beanServer = beanServer;
}
@Override
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;
/**
* Get all dependency resolvers, including those that belong to destroyed
- * things?
+ * things?.
*/
private List<DependencyResolverImpl> getAllSorted() {
transactionStatus.checkCommitStarted();
- List<DependencyResolverImpl> sorted = new ArrayList<>(
- moduleIdentifiersToDependencyResolverMap.values());
+ List<DependencyResolverImpl> sorted = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.values());
for (DependencyResolverImpl dri : sorted) {
dri.countMaxDependencyDepth(this);
}
}
public List<ModuleIdentifier> getSortedModuleIdentifiers() {
- List<ModuleIdentifier> result = new ArrayList<>(
- moduleIdentifiersToDependencyResolverMap.size());
+ List<ModuleIdentifier> result = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.size());
for (DependencyResolverImpl dri : getAllSorted()) {
ModuleIdentifier driName = dri.getIdentifier();
result.add(driName);
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;
}
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) {
cachedInstance = response;
}
return response;
- } catch(final InvocationTargetException e) {
+ } catch (final InvocationTargetException e) {
throw e.getCause();
} finally {
if (isGetInstance) {
}
}
- public void put(
- final ModuleIdentifier moduleIdentifier,
- final Module module,
- final ModuleFactory moduleFactory,
+ public void put(final ModuleIdentifier moduleIdentifier, final Module module, final ModuleFactory moduleFactory,
final ModuleInternalInfo maybeOldInternalInfo,
- final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
- final boolean isDefaultBean, final BundleContext bundleContext) {
+ final TransactionModuleJMXRegistration transactionModuleJMXRegistration, final boolean isDefaultBean,
+ final BundleContext bundleContext) {
transactionStatus.checkNotCommitted();
Class<? extends Module> moduleClass = Module.class;
if (module instanceof RuntimeBeanRegistratorAwareModule) {
moduleClass = RuntimeBeanRegistratorAwareModule.class;
}
- Module proxiedModule = Reflection.newProxy(moduleClass, new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
+ Module proxiedModule = Reflection.newProxy(moduleClass,
+ new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo(
- moduleIdentifier, proxiedModule, moduleFactory,
- maybeOldInternalInfo, transactionModuleJMXRegistration, isDefaultBean, module, bundleContext);
+ moduleIdentifier, proxiedModule, moduleFactory, maybeOldInternalInfo, transactionModuleJMXRegistration,
+ isDefaultBean, module, bundleContext);
modulesHolder.put(moduleInternalTransactionalInfo);
}
return modulesHolder.toCommitInfo();
}
- public Module findModule(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- return modulesHolder.findModule(moduleIdentifier,
- jmxAttributeForReporting);
+ public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
+ return modulesHolder.findModule(moduleIdentifier, jmxAttributeForReporting);
}
- public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier) {
+ public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
+ final ModuleIdentifier moduleIdentifier) {
return modulesHolder.findModuleInternalTransactionalInfo(moduleIdentifier);
}
public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- return modulesHolder.findModuleFactory(moduleIdentifier,
- jmxAttributeForReporting);
+ final JmxAttribute jmxAttributeForReporting) {
+ return modulesHolder.findModuleFactory(moduleIdentifier, jmxAttributeForReporting);
}
public Map<ModuleIdentifier, Module> getAllModules() {
return modulesHolder.getAllModules();
}
- public void assertNotExists(final ModuleIdentifier moduleIdentifier)
- throws InstanceAlreadyExistsException {
+ public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
modulesHolder.assertNotExists(moduleIdentifier);
}
modulesHolder.close();
deadlockMonitor.close();
}
-
}
/*
- * 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,
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,
}
@Override
+ @SuppressWarnings("IllegalCatch")
public void close() {
LOG.trace("Destroying {}", identifier);
try {
}
@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
/*
- * 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,
final ModuleFactory moduleFactory,
final ModuleInternalInfo maybeOldInternalInfo,
final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
- final boolean isDefaultBean, final Module realModule, final BundleContext bundleContext) {
+ final boolean isDefaultBean,
+ final Module realModule,
+ final BundleContext bundleContext) {
this.name = name;
this.proxiedModule = proxiedModule;
this.moduleFactory = moduleFactory;
/*
- * 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,
this.transactionIdentifier = transactionIdentifier;
}
-
public CommitInfo toCommitInfo() {
List<DestroyedModule> orderedDestroyedFromPreviousTransactions = new ArrayList<>(
unorderedDestroyedFromPreviousTransactions.size());
for (ModuleInternalTransactionalInfo toBeDestroyed : unorderedDestroyedFromPreviousTransactions) {
- orderedDestroyedFromPreviousTransactions.add(toBeDestroyed
- .toDestroyedModule());
+ orderedDestroyedFromPreviousTransactions.add(toBeDestroyed.toDestroyedModule());
}
Collections.sort(orderedDestroyedFromPreviousTransactions);
- return new CommitInfo(orderedDestroyedFromPreviousTransactions,
- commitMap);
+ return new CommitInfo(orderedDestroyedFromPreviousTransactions, commitMap);
}
- private ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
- final ModuleIdentifier moduleIdentifier,
+ private ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier,
final JmxAttribute jmxAttributeForReporting) {
- ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = commitMap
- .get(moduleIdentifier);
- JmxAttributeValidationException.checkNotNull(
- moduleInternalTransactionalInfo, "Module " + moduleIdentifier
- + "" + " not found in transaction " + transactionIdentifier,
+ ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = commitMap.get(moduleIdentifier);
+ JmxAttributeValidationException.checkNotNull(moduleInternalTransactionalInfo,
+ "Module " + moduleIdentifier + "" + " not found in transaction " + transactionIdentifier,
jmxAttributeForReporting);
return moduleInternalTransactionalInfo;
}
- public Module findModule(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- return findModuleInternalTransactionalInfo(moduleIdentifier,
- jmxAttributeForReporting).getProxiedModule();
+ public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
+ final ModuleIdentifier moduleIdentifier) {
+ ModuleInternalTransactionalInfo found = commitMap.get(moduleIdentifier);
+ if (found == null) {
+ throw new IllegalStateException("Not found:" + moduleIdentifier);
+ }
+ return found;
+ }
+
+ public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
+ return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getProxiedModule();
}
public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
final JmxAttribute jmxAttributeForReporting) {
- return findModuleInternalTransactionalInfo(moduleIdentifier,
- jmxAttributeForReporting).getModuleFactory();
+ return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getModuleFactory();
}
public Map<ModuleIdentifier, Module> getAllModules() {
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);
return found;
}
- public void assertNotExists(final ModuleIdentifier moduleIdentifier)
- throws InstanceAlreadyExistsException {
+ public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
if (commitMap.containsKey(moduleIdentifier)) {
- throw new InstanceAlreadyExistsException(
- "There is an instance registered with name " + moduleIdentifier);
+ throw new InstanceAlreadyExistsException("There is an instance registered with name " + moduleIdentifier);
}
}
- public Collection<ModuleInternalTransactionalInfo> getAllInfos(){
+ public Collection<ModuleInternalTransactionalInfo> getAllInfos() {
return commitMap.values();
}
- public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier) {
- ModuleInternalTransactionalInfo found = commitMap.get(moduleIdentifier);
- if (found == null) {
- throw new IllegalStateException("Not found:" + moduleIdentifier);
- }
- return found;
- }
-
@Override
public void close() {
unorderedDestroyedFromPreviousTransactions.clear();
/*
- * 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,
* provides additional functionality - namely it disallows setting attribute on
* a read only wrapper.
*/
-abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
+public abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
+
+ protected final Module module;
+ private final MBeanInfo mbeanInfo;
+ protected final ObjectName objectNameInternal;
+ protected final Map<String, AttributeHolder> attributeHolderMap;
+ protected final ModuleIdentifier moduleIdentifier;
+ protected final MBeanServer internalServer;
+
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
+
+ public AbstractDynamicWrapper(final Module module, final boolean writable, final ModuleIdentifier moduleIdentifier,
+ final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] operations,
+ final MBeanServer internalServer, final MBeanServer configMBeanServer) {
+ this.module = module;
+ this.moduleIdentifier = moduleIdentifier;
+ this.internalServer = internalServer;
+ this.objectNameInternal = thisWrapperObjectName;
+ // register the actual instance into an mbean server.
+ registerActualModule(objectNameInternal, configMBeanServer);
+ Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module.getClass());
+ this.attributeHolderMap = buildMBeanInfo(writable, moduleIdentifier, jmxInterfaces, objectNameInternal);
+ this.mbeanInfo = generateMBeanInfo(module, attributeHolderMap, operations, jmxInterfaces);
+ }
+
private static final class ModuleNotificationListener implements NotificationListener {
private final ObjectName objectNameInternal;
private final MBeanServer internalServer;
}
@Override
- public void handleNotification(final Notification n, final Object handback) {
- if (n instanceof MBeanServerNotification
- && n.getType()
- .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)
- && ((MBeanServerNotification) n).getMBeanName().equals(
- objectNameInternal)) {
+ public void handleNotification(final Notification notification, final Object handback) {
+ if (notification instanceof MBeanServerNotification
+ && notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)
+ && ((MBeanServerNotification) notification).getMBeanName().equals(objectNameInternal)) {
try {
internalServer.unregisterMBean(objectNameInternal);
- configMBeanServer.removeNotificationListener(
- MBeanServerDelegate.DELEGATE_NAME, this);
- } catch (MBeanRegistrationException
- | ListenerNotFoundException
- | InstanceNotFoundException e) {
+ configMBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this);
+ } catch (MBeanRegistrationException | ListenerNotFoundException | InstanceNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
}
- private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
- protected final Module module;
-
- private final MBeanInfo mbeanInfo;
- protected final ObjectName objectNameInternal;
- protected final Map<String, AttributeHolder> attributeHolderMap;
- protected final ModuleIdentifier moduleIdentifier;
- protected final MBeanServer internalServer;
-
- public AbstractDynamicWrapper(final Module module, final boolean writable,
- final ModuleIdentifier moduleIdentifier,
- final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] dOperations,
- final MBeanServer internalServer, final MBeanServer configMBeanServer) {
-
- this.module = module;
- this.moduleIdentifier = moduleIdentifier;
- this.internalServer = internalServer;
- this.objectNameInternal = thisWrapperObjectName;
- // register the actual instance into an mbean server.
- registerActualModule(objectNameInternal, configMBeanServer);
- Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module
- .getClass());
- this.attributeHolderMap = buildMBeanInfo(writable,
- moduleIdentifier, jmxInterfaces, objectNameInternal);
- this.mbeanInfo = generateMBeanInfo(module,
- attributeHolderMap, dOperations, jmxInterfaces);
- }
-
/**
* Register module into an internal mbean server, attach listener to the
* platform mbean server. Wait until this wrapper gets unregistered, in that
* case unregister the module and remove listener.
*/
- private final NotificationListener registerActualModule(final ObjectName objectNameInternal,
- final MBeanServer configMBeanServer) {
+ private NotificationListener registerActualModule(final ObjectName objectNameInternal,
+ final MBeanServer configMBeanServer) {
try {
internalServer.registerMBean(module, objectNameInternal);
- } catch (InstanceAlreadyExistsException | MBeanRegistrationException
- | NotCompliantMBeanException | IllegalStateException e) {
- throw new IllegalStateException(
- "Error occured during mbean registration with name " + objectNameInternal, e);
+ } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
+ | IllegalStateException e) {
+ throw new IllegalStateException("Error occured during mbean registration with name " + objectNameInternal,
+ e);
}
- NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer, configMBeanServer);
+ NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer,
+ configMBeanServer);
try {
- configMBeanServer.addNotificationListener(
- MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
+ configMBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
} catch (final InstanceNotFoundException e) {
throw new RuntimeException("Could not add notification listener", e);
}
}
private static MBeanInfo generateMBeanInfo(final Module module,
- final Map<String, AttributeHolder> attributeHolderMap,
- final MBeanOperationInfo[] dOperations, final Set<Class<?>> jmxInterfaces) {
+ final Map<String, AttributeHolder> attributeHolderMap, final MBeanOperationInfo[] operations,
+ final Set<Class<?>> jmxInterfaces) {
- String dDescription = findDescription(module.getClass(), jmxInterfaces);
- MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[0];
- List<MBeanAttributeInfo> attributes = new ArrayList<>(
- attributeHolderMap.size());
+ String description = findDescription(module.getClass(), jmxInterfaces);
+ MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
+ List<MBeanAttributeInfo> attributes = new ArrayList<>(attributeHolderMap.size());
for (AttributeHolder attributeHolder : attributeHolderMap.values()) {
attributes.add(attributeHolder.toMBeanAttributeInfo());
}
- return new MBeanInfo(module.getClass().getName(), dDescription,
- attributes.toArray(new MBeanAttributeInfo[0]), dConstructors,
- dOperations, new MBeanNotificationInfo[0]);
+ return new MBeanInfo(module.getClass().getName(), description, attributes.toArray(new MBeanAttributeInfo[0]),
+ constructors, operations, new MBeanNotificationInfo[0]);
}
static String findDescription(final Class<?> clazz, final Set<Class<?>> jmxInterfaces) {
- List<Description> descriptions = AnnotationsHelper
- .findClassAnnotationInSuperClassesAndIfcs(clazz, Description.class, jmxInterfaces);
+ List<Description> descriptions = AnnotationsHelper.findClassAnnotationInSuperClassesAndIfcs(clazz,
+ Description.class, jmxInterfaces);
return AnnotationsHelper.aggregateDescriptions(descriptions);
}
// inspect all exported interfaces ending with MXBean, extract getters &
// setters into attribute holder
private Map<String, AttributeHolder> buildMBeanInfo(final boolean writable, final ModuleIdentifier moduleIdentifier,
- final Set<Class<?>> jmxInterfaces,
- final ObjectName internalObjectName) {
+ final Set<Class<?>> jmxInterfaces, final ObjectName internalObjectName) {
// internal variables for describing MBean elements
Set<Method> methods = new HashSet<>();
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);
}
Map<String, AttributeHolder> attributeHolderMapLocal = new HashMap<>();
for (Method method : methods) {
- if (method.getParameterTypes().length == 1
- && method.getName().startsWith("set")) {
+ if (method.getParameterTypes().length == 1 && method.getName().startsWith("set")) {
Method setter;
String attribName = method.getName().substring(3);
try {
- setter = module.getClass().getMethod(method.getName(),
- method.getParameterTypes());
+ setter = module.getClass().getMethod(method.getName(), method.getParameterTypes());
} catch (final NoSuchMethodException e) {
- throw new RuntimeException("No such method on "
- + moduleIdentifier, e);
+ throw new RuntimeException("No such method on " + moduleIdentifier, e);
}
- RequireInterface ifc = AttributeHolder
- .findRequireInterfaceAnnotation(setter, jmxInterfaces);
+ RequireInterface ifc = AttributeHolder.findRequireInterfaceAnnotation(setter, jmxInterfaces);
String description = null;
if (ifc != null) {
- description = AttributeHolder.findDescription(setter,
- jmxInterfaces);
+ description = AttributeHolder.findDescription(setter, jmxInterfaces);
}
- AttributeHolder attributeHolder = new AttributeHolder(
- attribName, module, attributeMap.get(attribName)
- .getType(), writable, ifc, description);
+ AttributeHolder attributeHolder = new AttributeHolder(attribName, module,
+ attributeMap.get(attribName).getType(), writable, ifc, description);
attributeHolderMapLocal.put(attribName, attributeHolder);
}
}
@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);
}
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);
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);
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);
}
}
@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())) {
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));
}
}
/*
- * 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,
import java.util.Set;
import org.opendaylight.controller.config.api.annotations.Description;
-public class AnnotationsHelper {
+public final class AnnotationsHelper {
private AnnotationsHelper() {
}
/**
* Look for annotation specified by annotationType on method. First observe
- * method's class, then its super classes, then all provided interfaces.
- * Used for finding @Description and @RequireInterface
+ * method's class, then its super classes, then all provided interfaces. Used
+ * for finding @Description and @RequireInterface
*
* @param <T>
* generic type of annotation
* @return list of found annotations
*/
- static <T extends Annotation> List<T> findMethodAnnotationInSuperClassesAndIfcs(
- final Method setter, final Class<T> annotationType,
- final Set<Class<?>> inspectedInterfaces) {
+ static <T extends Annotation> List<T> findMethodAnnotationInSuperClassesAndIfcs(final Method setter,
+ final Class<T> annotationType, final Set<Class<?>> inspectedInterfaces) {
Builder<T> result = ImmutableSet.builder();
Class<?> inspectedClass = setter.getDeclaringClass();
do {
try {
- Method foundSetter = inspectedClass.getMethod(setter.getName(),
- setter.getParameterTypes());
+ Method foundSetter = inspectedClass.getMethod(setter.getName(), setter.getParameterTypes());
T annotation = foundSetter.getAnnotation(annotationType);
if (annotation != null) {
result.add(annotation);
throw new IllegalArgumentException(ifc + " is not an interface");
}
try {
- Method foundSetter = ifc.getMethod(setter.getName(),
- setter.getParameterTypes());
+ Method foundSetter = ifc.getMethod(setter.getName(), setter.getParameterTypes());
T annotation = foundSetter.getAnnotation(annotationType);
if (annotation != null) {
result.add(annotation);
}
} catch (final NoSuchMethodException e) {
-
+ break; // FIXME: is this ok?
}
}
return new ArrayList<>(result.build());
}
/**
- * Look for annotation specified by annotationType on type. First observe
- * class clazz, then its super classes, then all exported interfaces with
- * their super types. Used for finding @Description of modules.
+ * Look for annotation specified by annotationType on type. First observe class
+ * clazz, then its super classes, then all exported interfaces with their super
+ * types. Used for finding @Description of modules.
*
* @return list of found annotations
*/
- static <T extends Annotation> List<T> findClassAnnotationInSuperClassesAndIfcs(
- final Class<?> clazz, final Class<T> annotationType, final Set<Class<?>> interfaces) {
+ static <T extends Annotation> List<T> findClassAnnotationInSuperClassesAndIfcs(final Class<?> clazz,
+ final Class<T> annotationType, final Set<Class<?>> interfaces) {
List<T> result = new ArrayList<>();
Class<?> declaringClass = clazz;
do {
}
/**
+ * Lists aggregate descriptions.
+ *
* @return empty string if no annotation is found, or list of descriptions
* separated by newline
*/
/*
- * 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,
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();
}
}
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;
* Find @Description annotations in method class and all its exported
* interfaces.
*
- * @param setter
- * @param jmxInterfaces
+ * @param setter setter method
+ * @param jmxInterfaces JMX interfaces
* @return empty string if no annotation is found, or list of descriptions
- * separated by newline
+ * separated by newline
*/
static String findDescription(final Method setter, final Set<Class<?>> jmxInterfaces) {
- List<Description> descriptions = AnnotationsHelper
- .findMethodAnnotationInSuperClassesAndIfcs(setter, Description.class, jmxInterfaces);
+ List<Description> descriptions = AnnotationsHelper.findMethodAnnotationInSuperClassesAndIfcs(setter,
+ Description.class, jmxInterfaces);
return AnnotationsHelper.aggregateDescriptions(descriptions);
}
/**
- * Find @RequireInterface annotation by searching method class and all
- * exported interfaces.
+ * Find @RequireInterface annotation by searching method class and all exported
+ * interfaces.
*
- * @param setter
- * @param inspectedInterfaces
+ * @param setter setter method
+ * @param inspectedInterfaces interfaces
* @return null if no annotation is found, otherwise return the annotation
- * @throws IllegalStateException if more than one value is specified by found annotations
- * @throws IllegalArgumentException if set of exported interfaces contains non interface type
+ * @throws IllegalStateException
+ * if more than one value is specified by found annotations
+ * @throws IllegalArgumentException
+ * if set of exported interfaces contains non interface type
*/
static RequireInterface findRequireInterfaceAnnotation(final Method setter,
- final Set<Class<?>> inspectedInterfaces) {
+ final Set<Class<?>> inspectedInterfaces) {
- // only allow setX(ObjectName y) or setX(ObjectName[] y) or setX(List<ObjectName> y) to continue
+ // only allow setX(ObjectName y) or setX(ObjectName[] y) or
+ // setX(List<ObjectName> y) to continue
- if (setter.getParameterTypes().length > 1 ||
- !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) {
+ if (setter.getParameterTypes().length > 1
+ || !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) {
return null;
}
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);
}
/*
- * 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,
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) {
/*
- * 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,
*/
@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
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;
}
}
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;
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;
}
/*
- * 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,
/**
* Create instance.
*
+ * @param factoriesMap map of factories
* @throws IllegalArgumentException
* if unique constraint on module names is violated
*/
public HierarchicalConfigMBeanFactoriesHolder(
final Map<String, Map.Entry<ModuleFactory, BundleContext>> factoriesMap) {
- this.moduleNamesToConfigBeanFactories = Collections
- .unmodifiableMap(factoriesMap);
- moduleNames = Collections.unmodifiableSet(new TreeSet<>(
- moduleNamesToConfigBeanFactories.keySet()));
+ this.moduleNamesToConfigBeanFactories = Collections.unmodifiableMap(factoriesMap);
+ moduleNames = Collections.unmodifiableSet(new TreeSet<>(moduleNamesToConfigBeanFactories.keySet()));
List<ModuleFactory> factories = new ArrayList<>(this.moduleNamesToConfigBeanFactories.size());
- Collection<Map.Entry<ModuleFactory, BundleContext>> entryCollection = this.moduleNamesToConfigBeanFactories.values();
+ Collection<Map.Entry<ModuleFactory, BundleContext>> entryCollection = this.moduleNamesToConfigBeanFactories
+ .values();
for (Map.Entry<ModuleFactory, BundleContext> entry : entryCollection) {
factories.add(entry.getKey());
}
/**
* Get ModuleFactory by their name.
*
+ * @param moduleName
+ * module name
+ * @return module factory
* @throws IllegalArgumentException
* if factory is not found
*/
public List<ModuleFactory> getModuleFactories() {
return moduleFactories;
}
-
}
/*
- * 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,
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);
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);
}
}
/*
- * 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,
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) {
}
@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;
}
@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);
}
}
@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);
}
@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 {
/*
- * 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,
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;
final ModuleIdentifier moduleIdentifier) {
this.internalJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
this.moduleIdentifier = moduleIdentifier;
- defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(
- moduleIdentifier.getFactoryName(),
- moduleIdentifier.getInstanceName(),
- Collections.<String, String> emptyMap());
+ defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(moduleIdentifier.getFactoryName(),
+ moduleIdentifier.getInstanceName(), Collections.<String, String>emptyMap());
}
@Override
} catch (final InstanceAlreadyExistsException e) {
throw sanitize(e, moduleIdentifier, defaultRuntimeON);
}
- return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier,
- internalJMXRegistrator, Collections.<String, String> emptyMap());
+ return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier, internalJMXRegistrator,
+ Collections.<String, String>emptyMap());
}
@Override
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);
}
}
/*
- * 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,
}
@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;
@Override
public String toString() {
- return "ServiceReference{" +
- "serviceInterfaceName='" + serviceInterfaceName + '\'' +
- ", refName='" + refName + '\'' +
- '}';
+ return "ServiceReference{" + "serviceInterfaceName='" + serviceInterfaceName + '\'' + ", refName='" + refName
+ + '\'' + '}';
}
}
/*
- * 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,
String getNullableTransactionName();
- ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object,
- ObjectName on) throws InstanceAlreadyExistsException;
+ ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on)
+ throws InstanceAlreadyExistsException;
@Override
void close();
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;
}
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);
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;
}
/*
- * 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,
private static final String SERVICE_NAME_OSGI_PROP = "name";
/**
- * To be called for every created, reconfigured and recreated config bean.
- * It is expected that before using this method OSGi service registry will
- * be cleaned from previous registrations.
+ * To be called for every created, reconfigured and recreated config bean. It is
+ * expected that before using this method OSGi service registry will be cleaned
+ * from previous registrations.
+ *
+ * @param instance instance
+ * @param moduleIdentifier module identifier
+ * @param bundleContext bundle context
+ * @param serviceNamesToAnnotations service names annotations
+ * @return OSGI registration
*/
public OsgiRegistration registerToOsgi(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
- final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+ final BundleContext bundleContext,
+ final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations) {
return new OsgiRegistration(instance, moduleIdentifier, bundleContext, serviceNamesToAnnotations);
}
@GuardedBy("this")
private final Set<ServiceRegistration<?>> serviceRegistrations;
@GuardedBy("this")
- private final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations;
+ private final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations;
public OsgiRegistration(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
- final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+ final BundleContext bundleContext,
+ final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
this.instance = instance;
this.moduleIdentifier = moduleIdentifier;
this.serviceNamesToAnnotations = serviceNamesToAnnotations;
this.serviceRegistrations = registerToSR(instance, bundleContext, serviceNamesToAnnotations);
}
- private static Set<ServiceRegistration<?>> registerToSR(final AutoCloseable instance, final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
+ private static Set<ServiceRegistration<?>> registerToSR(final AutoCloseable instance,
+ final BundleContext bundleContext,
+ final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
Set<ServiceRegistration<?>> serviceRegistrations = new HashSet<>();
- for (Entry<ServiceInterfaceAnnotation, String /* service ref name */> entry : serviceNamesToAnnotations.entrySet()) {
+ for (Entry<ServiceInterfaceAnnotation, String /* service ref name */> entry : serviceNamesToAnnotations
+ .entrySet()) {
ServiceInterfaceAnnotation annotation = entry.getKey();
Class<?> requiredInterface = annotation.osgiRegistrationType();
- if(!annotation.registerToOsgi()) {
+ if (!annotation.registerToOsgi()) {
LOG.debug("registerToOsgi for service interface {} is false - not registering", requiredInterface);
continue;
}
- Preconditions.checkState(requiredInterface.isInstance(instance), instance.getClass().getName() +
- " instance should implement " + requiredInterface.getName());
+ Preconditions.checkState(requiredInterface.isInstance(instance),
+ instance.getClass().getName() + " instance should implement " + requiredInterface.getName());
Dictionary<String, String> propertiesForOsgi = createProps(entry.getValue());
- ServiceRegistration<?> serviceRegistration = bundleContext
- .registerService(requiredInterface.getName(), instance, propertiesForOsgi);
+ ServiceRegistration<?> serviceRegistration = bundleContext.registerService(requiredInterface.getName(),
+ instance, propertiesForOsgi);
serviceRegistrations.add(serviceRegistration);
}
return serviceRegistrations;
for (ServiceRegistration<?> serviceRegistration : serviceRegistrations) {
try {
serviceRegistration.unregister();
- } catch(final IllegalStateException e) {
+ } catch (final IllegalStateException e) {
LOG.trace("Cannot unregister {}", serviceRegistration, e);
}
}
serviceRegistrations.clear();
}
- public synchronized void updateRegistrations(final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
- final BundleContext bundleContext, final AutoCloseable newInstance) {
+ public synchronized void updateRegistrations(
+ final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
+ final BundleContext bundleContext, final AutoCloseable newInstance) {
boolean notEquals = !this.instance.equals(newInstance);
notEquals |= !newAnnotationMapping.equals(serviceNamesToAnnotations);
if (notEquals) {
- // FIXME: changing from old state to new state can be improved by computing the diff
+ // FIXME: changing from old state to new state can be improved by computing the
+ // diff
LOG.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
serviceNamesToAnnotations, newAnnotationMapping);
close();
/*
- * 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,
import org.slf4j.LoggerFactory;
/**
- * Every time factory is added or removed, blank transaction is triggered to handle
- * {@link org.opendaylight.controller.config.spi.ModuleFactory#getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory, org.osgi.framework.BundleContext)}
- * functionality.
+ * Every time factory is added or removed, blank transaction is triggered to
+ * handle.
*/
public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<ModuleFactory, Object> {
private static final Logger LOG = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
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
}
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 {
}
@Override
- public void modifiedService(final ServiceReference <ModuleFactory> moduleFactoryServiceReference, final Object o) {
+ public void modifiedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
+ final Object object) {
blankTransactionAsync();
}
@Override
- public void removedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference, final Object o) {
+ public void removedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
+ final Object object) {
blankTransactionAsync();
}
/*
- * 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,
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;
}
// 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.");
Map.Entry<ModuleFactory, BundleContext> conflicting = result.get(moduleName);
if (conflicting != null) {
String error = String.format(
- "Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
- moduleName, conflicting.getKey(), factory);
+ "Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
+ moduleName, conflicting.getKey(), factory);
LOG.error(error);
throw new IllegalArgumentException(error);
}
- result.put(moduleName, new AbstractMap.SimpleImmutableEntry<>(factory,
- serviceReference.getBundle().getBundleContext()));
+ result.put(moduleName,
+ new AbstractMap.SimpleImmutableEntry<>(factory, serviceReference.getBundle().getBundleContext()));
}
return result;
}
/*
- * 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,
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(
BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> moduleInfoResolvedBundleTracker =
new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE,
- moduleInfoBundleTracker);
+ moduleInfoBundleTracker);
ExtensibleBundleTracker<?> moduleFactoryBundleTracker = new ExtensibleBundleTracker<>(context,
moduleFactoryTracker);
moduleInfoBundleTracker.open(moduleInfoResolvedBundleTracker);
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) {
serviceTracker.open();
final AutoCloseable configMgrReg = OsgiRegistrationUtil.registerService(context, this,
- ConfigSystemService.class);
+ ConfigSystemService.class);
final List<AutoCloseable> list = Arrays.asList(bindingContextProvider, clsReg,
- OsgiRegistrationUtil.wrap(moduleFactoryBundleTracker), moduleInfoBundleTracker,
- configRegReg, configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications,
+ OsgiRegistrationUtil.wrap(moduleFactoryBundleTracker), moduleInfoBundleTracker, configRegReg,
+ configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications,
OsgiRegistrationUtil.wrap(serviceTracker), moduleInfoRegistryWrapper, notifyingConfigRegistry,
configMgrReg);
this.autoCloseable = OsgiRegistrationUtil.aggregate(list);
context.addBundleListener(this);
- } catch(final Exception e) {
- LOG.error("Error starting config manager", e);
- } catch(final Error e) {
- // Log JVM Error and re-throw. The OSGi container may silently fail the bundle and not always log
- // the exception. This has been seen on initial feature install.
+ } catch (final IllegalStateException e) {
LOG.error("Error starting config manager", e);
- throw e;
}
LOG.info("Config manager start complete");
@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();
}
}
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
/**
- *
* Extensible bundle tracker. Takes several BundleTrackerCustomizers and
* propagates bundle events to all of them.
*
- * Primary customizer may return tracking object,
- * which will be passed to it during invocation of
+ * <p>
+ * Primary customizer may return tracking object, which will be passed to it
+ * during invocation of
* {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)}
*
+ * <p>
+ * This extender modifies behavior to not leak platform thread in
+ * {@link BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)} but deliver
+ * this event from its own single threaded executor.
*
- * This extender modifies behaviour to not leak platform thread
- * in {@link BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)}
- * but deliver this event from its own single threaded executor.
- *
- * If bundle is removed before event for adding bundle was executed,
- * that event is cancelled. If addingBundle event is currently in progress
- * or was already executed, platform thread is block untill addingBundle
- * finishes so bundle could be removed correctly in platform thread.
- *
+ * <p>
+ * If bundle is removed before event for adding bundle was executed, that event
+ * is cancelled. If addingBundle event is currently in progress or was already
+ * executed, platform thread is block until addingBundle finishes so bundle
+ * could be removed correctly in platform thread.
*
- * Method {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)}
- * is never invoked on registered trackers.
+ * <p>
+ * Method
+ * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} is
+ * never invoked on registered trackers.
*
- * @param <T>
+ * @param <T> value
*/
public final class ExtensibleBundleTracker<T> extends BundleTracker<Future<T>> {
private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
- .setNameFormat("config-bundle-tracker-%d").build();
+ .setNameFormat("config-bundle-tracker-%d").build();
private final ExecutorService eventExecutor;
private final BundleTrackerCustomizer<T> primaryTracker;
private final BundleTrackerCustomizer<?>[] additionalTrackers;
private static final Logger LOG = LoggerFactory.getLogger(ExtensibleBundleTracker.class);
- public ExtensibleBundleTracker(final BundleContext context, final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
+ public ExtensibleBundleTracker(final BundleContext context,
+ final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
final BundleTrackerCustomizer<?>... additionalBundleTrackerCustomizers) {
this(context, Bundle.ACTIVE, primaryBundleTrackerCustomizer, additionalBundleTrackerCustomizers);
}
@Override
public Future<T> addingBundle(final Bundle bundle, final BundleEvent event) {
- LOG.trace("Submiting AddingBundle for bundle {} and event {} to be processed asynchronously",bundle,event);
+ LOG.trace("Submiting AddingBundle for bundle {} and event {} to be processed asynchronously", bundle, event);
return eventExecutor.submit(() -> {
- try {
- T primaryTrackerRetVal = primaryTracker.addingBundle(bundle, event);
+ T primaryTrackerRetVal = primaryTracker.addingBundle(bundle, event);
- forEachAdditionalBundle(tracker -> tracker.addingBundle(bundle, event));
- LOG.trace("AddingBundle for {} and event {} finished successfully",bundle,event);
- return primaryTrackerRetVal;
- } catch (final Exception e) {
- LOG.error("Failed to add bundle {}", bundle, e);
- throw e;
- }
+ forEachAdditionalBundle(tracker -> tracker.addingBundle(bundle, event));
+ LOG.trace("AddingBundle for {} and event {} finished successfully", bundle, event);
+ return primaryTrackerRetVal;
});
}
@Override
public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
// Intentionally NOOP
-
}
@Override
public void removedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
- if(!object.isDone() && object.cancel(false)) {
+ if (!object.isDone() && object.cancel(false)) {
// We canceled adding event before it was processed
// so it is safe to return
- LOG.trace("Adding Bundle event for {} was cancelled. No additional work required.",bundle);
+ LOG.trace("Adding Bundle event for {} was cancelled. No additional work required.", bundle);
return;
}
try {
- LOG.trace("Invoking removedBundle event for {}",bundle);
+ LOG.trace("Invoking removedBundle event for {}", bundle);
primaryTracker.removedBundle(bundle, event, object.get());
forEachAdditionalBundle(tracker -> tracker.removedBundle(bundle, event, null));
- LOG.trace("Removed bundle event for {} finished successfully.",bundle);
- } catch (final Exception e) {
+ LOG.trace("Removed bundle event for {} finished successfully.", bundle);
+ } catch (final ExecutionException | InterruptedException e) {
LOG.error("Failed to remove bundle {}", bundle, e);
}
}
private interface BundleStrategy {
void execute(BundleTrackerCustomizer<?> tracker);
}
-
}
/*
- * 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,
* line should contain an implementation of ModuleFactory interface. Creates new
* instance with default constructor and registers it into OSGi service
* registry. There is no need for listening for implementing removedBundle as
- * the services are unregistered automatically.
- * Code based on http://www.toedter.com/blog/?p=236
+ * the services are unregistered automatically. Code based on
+ * http://www.toedter.com/blog/?p=236
*/
public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boolean> {
private final BlankTransactionServiceTracker blankTransactionServiceTracker;
@Override
public Boolean addingBundle(final Bundle bundle, final BundleEvent event) {
URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
- LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
- bundle, resource, event);
+ LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}", bundle, resource, event);
if (resource != null) {
try {
for (String factoryClassName : Resources.readLines(resource, StandardCharsets.UTF_8)) {
@Override
public void removedBundle(final Bundle bundle, final BundleEvent event, final Boolean hasFactory) {
- if(hasFactory) {
+ if (hasFactory) {
// workaround for service tracker not getting removed service event
blankTransactionServiceTracker.blankTransactionSync();
}
Class<?> clazz = bundle.loadClass(factoryClassName);
if (ModuleFactory.class.isAssignableFrom(clazz)) {
try {
- LOG.debug("Registering {} in bundle {}",
- clazz.getName(), bundle);
- return bundle.getBundleContext().registerService(
- ModuleFactory.class.getName(), clazz.newInstance(),
+ LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
+ return bundle.getBundleContext().registerService(ModuleFactory.class.getName(), clazz.newInstance(),
null);
} catch (final InstantiationException e) {
- errorMessage = logMessage(
- "Could not instantiate {} in bundle {}, reason {}",
- factoryClassName, bundle, e);
+ errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", factoryClassName,
+ bundle, e);
ex = e;
} catch (final IllegalAccessException e) {
- errorMessage = logMessage(
- "Illegal access during instantiation of class {} in bundle {}, reason {}",
+ errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
factoryClassName, bundle, e);
ex = e;
}
} else {
- errorMessage = logMessage(
- "Class {} does not implement {} in bundle {}", clazz,
- ModuleFactory.class, bundle);
+ errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz, ModuleFactory.class,
+ bundle);
}
} catch (final ClassNotFoundException e) {
- errorMessage = logMessage(
- "Could not find class {} in bundle {}, reason {}",
- factoryClassName, bundle, e);
+ errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", factoryClassName, bundle, e);
ex = e;
}
/*
- * 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,
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());
}
/*
- * 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,
import org.slf4j.LoggerFactory;
/**
- * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed into ModuleInfoRegistry
+ * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed
+ * into ModuleInfoRegistry.
*/
-public final class ModuleInfoBundleTracker implements AutoCloseable,
- BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
+public final class ModuleInfoBundleTracker
+ implements AutoCloseable, BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
}
@Override
+ @SuppressWarnings("IllegalCatch")
public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(final Bundle bundle, final BundleEvent event) {
URL resource = bundle.getEntry(YANG_MODULE_INFO_SERVICE_PATH);
LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
}
- if(!starting) {
+ if (!starting) {
moduleInfoRegistry.updateService();
}
} catch (final IOException e) {
}
@Override
+ @SuppressWarnings("IllegalCatch")
public void removedBundle(final Bundle bundle, final BundleEvent event,
final Collection<ObjectRegistration<YangModuleInfo>> regs) {
if (regs == null) {
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;
throw new IllegalStateException(errorMessage, e);
}
- try{
+ try {
return instance.getModuleInfo();
} catch (NoClassDefFoundError | ExceptionInInitializerError e) {
throw new IllegalStateException("Error while executing getModuleInfo on " + instance, e);
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);
}
}
/*
- * 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,
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
- * Update SchemaContext service in Service Registry each time new YangModuleInfo is added or removed.
+ * Update SchemaContext service in Service Registry each time new YangModuleInfo
+ * is added or removed.
*/
public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(RefreshingSCPModuleInfoRegistry.class);
-
private final ModuleInfoRegistry moduleInfoRegistry;
private final SchemaContextProvider schemaContextProvider;
private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
private volatile ServiceRegistration<SchemaContextProvider> osgiReg;
public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry,
- final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat,
- final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final BindingContextProvider bindingContextProvider,
- final BundleContext bundleContext) {
+ final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat,
+ final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
+ final BindingContextProvider bindingContextProvider, final BundleContext bundleContext) {
this.moduleInfoRegistry = moduleInfoRegistry;
this.schemaContextProvider = schemaContextProvider;
this.classLoadingStrat = classLoadingStrat;
this.sourceProvider = sourceProvider;
this.bindingContextProvider = bindingContextProvider;
- this.osgiReg = bundleContext
- .registerService(SchemaContextProvider.class, schemaContextProvider, new Hashtable<String, String>());
+ this.osgiReg = bundleContext.registerService(SchemaContextProvider.class, schemaContextProvider,
+ new Hashtable<String, String>());
}
public synchronized void updateService() {
if (this.osgiReg != null) {
- try {
- this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider);
-
- final Dictionary<String, Object> props = new Hashtable<>();
- props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext());
- props.put(SchemaSourceProvider.class.getName(), this.sourceProvider);
- // send modifiedService event
- this.osgiReg.setProperties(props);
- } catch (final RuntimeException e) {
- // The ModuleInfoBackedContext throws a RuntimeException if it can't create the schema context.
- LOG.warn("Error updating the BindingContextProvider", e);
- }
+ this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider);
+
+ final Dictionary<String, Object> props = new Hashtable<>();
+ props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext());
+ props.put(SchemaSourceProvider.class.getName(), this.sourceProvider);
+ // send modifiedService event
+ this.osgiReg.setProperties(props);
}
}
@Override
public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
- final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry.registerModuleInfo(yangModuleInfo);
+ final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry
+ .registerModuleInfo(yangModuleInfo);
return new ObjectRegistrationWrapper(yangModuleInfoObjectRegistration);
}
/*
- * 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,
public static Set<Class<?>> getAllInterfaces(Class<?> clazz) {
if (clazz.isInterface()) {
- throw new IllegalArgumentException(clazz
- + " should not be an interface");
+ throw new IllegalArgumentException(clazz + " should not be an interface");
}
// getInterfaces gets interfaces implemented directly by this class
Set<Class<?>> toBeInspected = new HashSet<>();
Iterator<Class<?>> iterator = interfaces.iterator();
Class<?> ifc = iterator.next();
iterator.remove();
- if (!ifc.isInterface()) {
+ if (!ifc.isInterface()) {
throw new IllegalArgumentException(ifc + " should be an interface");
}
interfaces.addAll(Arrays.asList(ifc.getInterfaces()));
/**
* Get interfaces that this class is derived from that are JMX interfaces.
+ *
+ * @param configBeanClass
+ * config bean class
+ * @return set containing classes
*/
- public static Set<Class<?>> getMXInterfaces(
- final Class<? extends Module> configBeanClass) {
+ public static Set<Class<?>> getMXInterfaces(final Class<? extends Module> configBeanClass) {
Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : allInterfaces) {
* Get all implemented interfaces that have
* {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation}
* annotation.
+ *
+ * @param configBeanClass
+ * config bean class
+ * @return set containing classes
*/
- public static Set<Class<?>> getServiceInterfaces(
- final Class<? extends Module> configBeanClass) {
+ public static Set<Class<?>> getServiceInterfaces(final Class<? extends Module> configBeanClass) {
Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : allInterfaces) {
if (AbstractServiceInterface.class.isAssignableFrom(clazz)) {
- ServiceInterfaceAnnotation annotation = clazz
- .getAnnotation(ServiceInterfaceAnnotation.class);
+ ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
if (annotation != null) {
result.add(clazz);
}
return result;
}
- public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(final Class<? extends Module> configBeanClass) {
+ public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(
+ final Class<? extends Module> configBeanClass) {
Set<Class<? extends AbstractServiceInterface>> foundGeneratedSIClasses = new HashSet<>();
for (Class<?> clazz : getAllInterfaces(configBeanClass)) {
- if (AbstractServiceInterface.class.isAssignableFrom(clazz) && !AbstractServiceInterface.class.equals(clazz)) {
+ if (AbstractServiceInterface.class.isAssignableFrom(clazz)
+ && !AbstractServiceInterface.class.equals(clazz)) {
foundGeneratedSIClasses.add((Class<? extends AbstractServiceInterface>) clazz);
}
}
return getAllAbstractServiceInterfaceClasses(foundGeneratedSIClasses);
}
-
/**
* Get OSGi registration types under which config bean instance should be
* registered. This is specified in
* {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation#osgiRegistrationType()}
+ *
+ * @param configBeanClass config bean class
+ * @return set of classes
*/
- public static Set<Class<?>> getOsgiRegistrationTypes(
- final Class<? extends Module> configBeanClass) {
+ public static Set<Class<?>> getOsgiRegistrationTypes(final Class<? extends Module> configBeanClass) {
Set<Class<?>> serviceInterfaces = getServiceInterfaces(configBeanClass);
Set<Class<?>> result = new HashSet<>();
for (Class<?> clazz : serviceInterfaces) {
- ServiceInterfaceAnnotation annotation = clazz
- .getAnnotation(ServiceInterfaceAnnotation.class);
+ ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
result.add(annotation.osgiRegistrationType());
}
return result;
}
public static Set<String> getQNames(final Set<ServiceInterfaceAnnotation> siAnnotations) {
- Set<String> qNames = new HashSet<>();
- for (ServiceInterfaceAnnotation sia: siAnnotations) {
- qNames.add(sia.value());
+ Set<String> names = new HashSet<>();
+ for (ServiceInterfaceAnnotation sia : siAnnotations) {
+ names.add(sia.value());
}
- return ImmutableSet.copyOf(qNames);
+ return ImmutableSet.copyOf(names);
}
public static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final ModuleFactory factory) {
- Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections.unmodifiableSet(factory.getImplementedServiceIntefaces());
+ Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections
+ .unmodifiableSet(factory.getImplementedServiceIntefaces());
return getServiceInterfaceAnnotations(implementedServiceIntefaces);
}
- private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
- Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(implementedServiceIntefaces);
+ private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(
+ final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
+ Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(
+ implementedServiceIntefaces);
Set<ServiceInterfaceAnnotation> result = new HashSet<>();
- // SIs can form hierarchies, inspect superclass until it does not extend AbstractSI
+ // SIs can form hierarchies, inspect superclass until it does not extend
+ // AbstractSI
for (Class<?> clazz : inspected) {
ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
if (annotation != null) {
Set<Class<?>> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs);
Set<Class<? extends AbstractServiceInterface>> result = new HashSet<>();
- for(Class<?> ifc: allInterfaces){
- if (AbstractServiceInterface.class.isAssignableFrom(ifc) &&
- !ifc.equals(AbstractServiceInterface.class)) {
+ for (Class<?> ifc : allInterfaces) {
+ if (AbstractServiceInterface.class.isAssignableFrom(ifc) && !ifc.equals(AbstractServiceInterface.class)) {
result.add((Class<? extends AbstractServiceInterface>) ifc);
}
-
}
return result;
}
/*
- * 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,
import org.opendaylight.yangtools.yang.common.QName;
import org.osgi.framework.BundleContext;
-public class ModuleQNameUtil {
+public final class ModuleQNameUtil {
private 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();
}
}
return result;
}
-
}
/*
- * 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,
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;
}
@SafeVarargs
- public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class<? super T> ... interfaces) {
+ public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service,
+ final Class<? super T>... interfaces) {
checkNotNull(service);
checkNotNull(interfaces);
List<AutoCloseable> autoCloseableList = new ArrayList<>();
return serviceTracker::close;
}
- /**
- * Close list of auto closeables in reverse order
- */
+ @SuppressWarnings("IllegalCatch")
public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
checkNotNull(list);
/*
- * 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,
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 {
}
}
}
-
}
/*
- * 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,
* 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 {
}
// Default handler for OSGi service registration
- protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
+ protected static class RecordingBundleContextServiceRegistrationHandler
+ implements BundleContextServiceRegistrationHandler {
private final List<RegistrationHolder> registrations = new LinkedList<>();
+
@Override
- public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance, final Dictionary<String, ?> props) {
+ public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance,
+ final Dictionary<String, ?> props) {
this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
}
}
}
- protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(final Class<?> serviceType) {
+ protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(
+ final Class<?> serviceType) {
return this.currentBundleContextServiceRegistrationHandler;
}
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 {
private void initBundleContext() {
doNothing().when(this.mockedServiceRegistration).unregister();
final RegisterServiceAnswer answer = new RegisterServiceAnswer();
- doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
- doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(), Matchers.<Dictionary<String, ?>>any());
+ doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(),
+ Matchers.<Dictionary<String, ?>>any());
+ doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(),
+ Matchers.<Dictionary<String, ?>>any());
}
@After
}
/**
- * Can be called in @After of tests if some other cleanup is needed that
- * would be discarded by closing config beans in this method
+ * Can be called in @After of tests if some other cleanup is needed that would
+ * be discarded by closing config beans in this method.
*/
protected void destroyAllConfigBeans() throws Exception {
- final ConfigTransactionJMXClient transaction = this.configRegistryClient
- .createTransaction();
+ final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
Set<ObjectName> all = transaction.lookupConfigBeans();
// workaround for getting same Module more times
while (all.size() > 0) {
final int expectedRecreatedInstances, final int expectedReusedInstances) {
assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
- status.getRecreatedInstances().size());
+ status.getRecreatedInstances().size());
assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
- status.getReusedInstances().size());
+ status.getReusedInstances().size());
}
-
- protected void assertBeanCount(final int i, final String configMXBeanName) {
- assertEquals(i, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
+ protected void assertBeanCount(final int index, final String configMXBeanName) {
+ assertEquals(index, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
}
/**
+ * Empty constructor.
*
* @param configBeanClass
- * Empty constructor class of config bean to be instantiated
- * whenever create
- * @param implementationName
- * @return
+ * Empty constructor class of config bean to be instantiated whenever
+ * create
+ * @param implementationName name
+ * @return factory
*/
protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
final String implementationName) {
final Object serviceTypeRaw = args[0];
final Object serviceInstance = args[1];
@SuppressWarnings("unchecked")
- final
- Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
+ final Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
if (serviceTypeRaw instanceof Class) {
final Class<?> serviceType = (Class<?>) serviceTypeRaw;
} else if (serviceTypeRaw instanceof String) {
invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
} else {
- throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
+ throw new IllegalStateException(
+ "Not handling service registration of type, Unknown type" + serviceTypeRaw);
}
return AbstractConfigTest.this.mockedServiceRegistration;
}
- public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary<String, ?> props) {
+ public void invokeServiceHandler(final Object serviceInstance, final String className,
+ final Dictionary<String, ?> props) {
try {
final Class<?> serviceType = Class.forName(className);
invokeServiceHandler(serviceInstance, serviceType, props);
} catch (final ClassNotFoundException e) {
- throw new IllegalStateException("Not handling service registration of type " + className, e);
+ throw new IllegalStateException("Not handling service registration of type " + className, e);
}
}
- private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType, final Dictionary<String, ?> props) {
- final BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
+ private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType,
+ final Dictionary<String, ?> props) {
+ final BundleContextServiceRegistrationHandler serviceRegistrationHandler =
+ getBundleContextServiceRegistrationHandler(serviceType);
if (serviceRegistrationHandler != null) {
serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
}
/**
- * Expand inner exception wrapped by JMX
+ * Expand inner exception wrapped by JMX.
*
- * @param innerObject jmx proxy which will be wrapped and returned
+ * @param innerObject
+ * jmx proxy which will be wrapped and returned
*/
protected <T> T rethrowCause(final T innerObject) {
@SuppressWarnings("unchecked")
- final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
+ final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
+ try {
+ return method.invoke(innerObject, args);
+ } catch (final InvocationTargetException e) {
try {
- return method.invoke(innerObject, args);
- } catch (final InvocationTargetException e) {
- try {
- throw e.getTargetException();
- } catch (final RuntimeMBeanException e2) {
- throw e2.getTargetException();
- }
+ throw e.getTargetException();
+ } catch (final RuntimeMBeanException e2) {
+ throw e2.getTargetException();
}
}
- );
+ });
return proxy;
}
/**
- * removes contents of the directory
- * @param dir to be cleaned
- * @throws IOException
+ * removes contents of the directory.
+ *
+ * @param dir
+ * to be cleaned
+ * @throws IOException IO exception
*/
protected void cleanDirectory(final File dir) throws IOException {
if (!dir.isDirectory()) {
/*
- * 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,
* 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 {
-
}
-
}
/*
- * 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,
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
public ModuleIdentifier getIdentifier() {
return id;
}
-
}
/*
- * 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,
/**
* 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 {
private final Class<? extends Module> configBeanClass;
/**
+ * Module factory constructor.
+ *
* @param implementationName
+ * name of the implementation
* @param configBeanClass
- * class that will be instantiated when createModule is called.
- * This class must implement Module interface and all exported
- * interfaces.
+ * class that will be instantiated when createModule is called. This
+ * class must implement Module interface and all exported interfaces.
*/
- public ClassBasedModuleFactory(final String implementationName,
- final Class<? extends Module> configBeanClass) {
+ public ClassBasedModuleFactory(final String implementationName, final Class<? extends Module> configBeanClass) {
this.implementationName = implementationName;
this.configBeanClass = configBeanClass;
}
}
@Override
- public Module createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
- throws Exception {
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
Preconditions.checkNotNull(old);
return constructModule(instanceName, dependencyResolver, old);
}
- private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old) throws InstantiationException, IllegalAccessException, InvocationTargetException {
+ @Override
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
+ try {
+ return constructModule(instanceName, dependencyResolver, null);
+ } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final DynamicMBeanWithInstance old)
+ throws InstantiationException, IllegalAccessException, InvocationTargetException {
Preconditions.checkNotNull(dependencyResolver);
ModuleIdentifier moduleIdentifier = new ModuleIdentifier(implementationName, instanceName);
Constructor<? extends Module> declaredConstructor;
try {
- declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class, ModuleIdentifier.class);
+ declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class,
+ ModuleIdentifier.class);
} catch (final NoSuchMethodException e) {
throw new IllegalStateException(
- "Did not find constructor with parameters (DynamicMBeanWithInstance) in "
- + configBeanClass, e);
+ "Did not find constructor with parameters (DynamicMBeanWithInstance) in " + configBeanClass, e);
}
Preconditions.checkState(declaredConstructor != null);
return declaredConstructor.newInstance(old, moduleIdentifier);
}
- @Override
- public Module createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- try {
- return constructModule(instanceName, dependencyResolver, null);
- } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
@Override
public boolean isModuleImplementingServiceInterface(
final Class<? extends AbstractServiceInterface> serviceInterface) {
}
@Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext bundleContext) {
return new HashSet<>();
}
/*
- * 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,
import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean;
-public class ConfigRegistryImplLookupTest extends
- AbstractLockedPlatformMBeanServerTest {
+public class ConfigRegistryImplLookupTest extends AbstractLockedPlatformMBeanServerTest {
private ConfigRegistryImpl configRegistryImpl;
private BaseJMXRegistrator baseJMXRegistrator;
- private static final String moduleNameA = "moduleA";
- private static final String moduleNameB = "moduleB";
+ private static final String MODULE_NAMEA = "moduleA";
+ private static final String MODULE_NAMEB = "moduleB";
- private static final String instanceNameA = "instA";
- private static final String instanceNameB = "instB";
- private static final String instanceNameC = "instC";
+ private static final String INSTANCE_NAMEA = "instA";
+ private static final String INSTANCE_NAMEB = "instB";
+ private static final String INSTANCE_NAMEC = "instC";
- private static final ObjectName name1 = ObjectNameUtil
- .createReadOnlyModuleON(moduleNameA, instanceNameA);
- private static final ObjectName name2 = ObjectNameUtil
- .createReadOnlyModuleON(moduleNameA, instanceNameB);
- private static final ObjectName name3 = ObjectNameUtil
- .createReadOnlyModuleON(moduleNameA, instanceNameC);
- private static final ObjectName name4 = ObjectNameUtil
- .createReadOnlyModuleON(moduleNameB, instanceNameA);
+ private static final ObjectName NAME1 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEA);
+ private static final ObjectName NAME2 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEB);
+ private static final ObjectName NAME3 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEC);
+ private static final ObjectName NAME4 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEB, INSTANCE_NAMEA);
- private static final ObjectName name5 = ObjectNameUtil
- .createRuntimeBeanName(moduleNameA, instanceNameA, Collections.<String, String>emptyMap());
- private static final ObjectName name6 = ObjectNameUtil
- .createRuntimeBeanName(moduleNameA, instanceNameB, Collections.<String, String>emptyMap());
- private static final ObjectName name8 = ObjectNameUtil
- .createRuntimeBeanName(moduleNameB, instanceNameA, Collections.<String, String>emptyMap());
+ private static final ObjectName NAME5 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEA,
+ Collections.<String, String>emptyMap());
+ private static final ObjectName NAME6 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEB,
+ Collections.<String, String>emptyMap());
+ private static final ObjectName NAME8 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEB, INSTANCE_NAMEA,
+ Collections.<String, String>emptyMap());
- private static final ObjectName name9 = ObjectNameUtil
- .createTransactionModuleON("transaction", moduleNameA, instanceNameA);
+ private static final ObjectName NAME9 = ObjectNameUtil.createTransactionModuleON("transaction", MODULE_NAMEA,
+ INSTANCE_NAMEA);
@Before
public void setUp() throws Exception {
- configRegistryImpl = new ConfigRegistryImpl(null,
- ManagementFactory.getPlatformMBeanServer(), null);
- Field field = configRegistryImpl.getClass().getDeclaredField(
- "baseJMXRegistrator");
+ configRegistryImpl = new ConfigRegistryImpl(null, ManagementFactory.getPlatformMBeanServer(), null);
+ Field field = configRegistryImpl.getClass().getDeclaredField("baseJMXRegistrator");
field.setAccessible(true);
baseJMXRegistrator = (BaseJMXRegistrator) field.get(configRegistryImpl);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name1);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name2);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name3);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, name4);
+ registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME1);
+ registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME2);
+ registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME3);
+ registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME4);
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name5);
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name6);
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, name8);
+ registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME5);
+ registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME6);
+ registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME8);
- baseJMXRegistrator.createTransactionJMXRegistrator("transaction")
- .createTransactionModuleJMXRegistrator()
- .registerMBean(new TestingRuntimeBean(), name9);
+ baseJMXRegistrator.createTransactionJMXRegistrator("transaction").createTransactionModuleJMXRegistrator()
+ .registerMBean(new TestingRuntimeBean(), NAME9);
}
private static void registerModuleBean(final TestingRuntimeBean testingRuntimeBean,
final BaseJMXRegistrator baseJMXRegistrator, final ObjectName objectName)
throws InstanceAlreadyExistsException {
- baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(
- testingRuntimeBean, objectName);
+ baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(testingRuntimeBean, objectName);
}
private static void registerRuntimeBean(final RuntimeBean object, final BaseJMXRegistrator baseJMXRegistrator,
final ObjectName runtimeON) throws InstanceAlreadyExistsException {
String factoryName = ObjectNameUtil.getFactoryName(runtimeON);
String instanceName = ObjectNameUtil.getInstanceName(runtimeON);
- Map<String, String> properties = ObjectNameUtil
- .getAdditionalPropertiesOfRuntimeBeanName(runtimeON);
+ Map<String, String> properties = ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(runtimeON);
RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
.createRuntimeBeanRegistrator(new ModuleIdentifier(factoryName, instanceName));
@Test
public void testLookupConfigBeans() throws Exception {
Set<ObjectName> beans = configRegistryImpl.lookupConfigBeans();
- assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans);
+ assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
beans = configRegistryImpl.lookupConfigBeans();
- assertEquals(Sets.newHashSet(name1, name2, name3, name4), beans);
+ assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
}
@Test
public void testLookupConfigBeanWithModuleName() throws Exception {
- Set<ObjectName> bean = configRegistryImpl
- .lookupConfigBeans(moduleNameA);
- assertEquals(Sets.newHashSet(name1, name2, name3), bean);
+ Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA);
+ assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), bean);
}
@Test
- public void testLookupConfigBeanWithModuleNameAndInstanceName()
- throws Exception {
- Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(
- moduleNameA, instanceNameA);
- assertEquals(Sets.newHashSet(name1), bean);
+ public void testLookupConfigBeanWithModuleNameAndInstanceName() throws Exception {
+ Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA, INSTANCE_NAMEA);
+ assertEquals(Sets.newHashSet(NAME1), bean);
}
@Test
public void testLookupRuntimeBeans() throws Exception {
Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans();
- assertEquals(Sets.newHashSet(name5, name6, name8), beans);
+ assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
beans = configRegistryImpl.lookupRuntimeBeans(null, null);
- assertEquals(Sets.newHashSet(name5, name6, name8), beans);
+ assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
}
@Test
public void testLookupRuntimeBeansWithIFcNameAndImplName() throws Exception {
- Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans(
- moduleNameA, instanceNameA);
- assertEquals(Sets.newHashSet(name5), beans);
+ Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans(MODULE_NAMEA, INSTANCE_NAMEA);
+ assertEquals(Sets.newHashSet(NAME5), beans);
}
-
}
/*
- * 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,
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-public class ConfigTransactionControllerImplTest extends
- AbstractLockedPlatformMBeanServerTest {
+public class ConfigTransactionControllerImplTest extends AbstractLockedPlatformMBeanServerTest {
private BaseJMXRegistrator baseJMXRegistrator;
private ConfigTransactionControllerImpl testedTxController;
private MBeanServer transactionsMBeanServer;
- private static final String transactionName123 = "testTX1";
- private static final String transactionName4 = "testTX2";
+ private static final String TRANSACTION_NAME123 = "testTX1";
+ private static final String TRANSACTION_NAME4 = "testTX2";
- private static final String moduleName124 = "module124";
- private static final String moduleName3 = "module3";
+ private static final String MODULE_NAME124 = "module124";
+ private static final String MODULE_NAME3 = "module3";
- private static final String instanceName134 = "instA";
- private static final String instanceName2 = "instB";
+ private static final String INSTANCE_NAME134 = "instA";
+ private static final String INSTANCE_NAME2 = "instB";
- private static final ObjectName name1 = ObjectNameUtil
- .createTransactionModuleON(transactionName123, moduleName124, instanceName134);
- private static final ObjectName name2 = ObjectNameUtil
- .createTransactionModuleON(transactionName123, moduleName124, instanceName2);
- private static final ObjectName name3 = ObjectNameUtil
- .createTransactionModuleON(transactionName123, moduleName3, instanceName134);
- private static final ObjectName name4 = ObjectNameUtil
- .createTransactionModuleON(transactionName4, moduleName124, instanceName134);
+ private static final ObjectName NAME1 =
+ ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME124, INSTANCE_NAME134);
+ private static final ObjectName NAME2 =
+ ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123,
+ MODULE_NAME124, INSTANCE_NAME2);
+ private static final ObjectName NAME3 =
+ ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME3, INSTANCE_NAME134);
+ private static final ObjectName NAME4 =
+ ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME4, MODULE_NAME124, INSTANCE_NAME134);
@Before
public void setUp() throws Exception {
- baseJMXRegistrator = new BaseJMXRegistrator(
- ManagementFactory.getPlatformMBeanServer());
+ baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
transactionsMBeanServer = MBeanServerFactory.createMBeanServer();
Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories = new HashMap<>();
ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
- new TransactionIdentifier(transactionName123), () ->
- baseJMXRegistrator.createTransactionJMXRegistrator(transactionName123), currentlyRegisteredFactories);
+ new TransactionIdentifier(TRANSACTION_NAME123),
+ () -> baseJMXRegistrator.createTransactionJMXRegistrator(TRANSACTION_NAME123),
+ currentlyRegisteredFactories);
- SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
- ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(), txLookupRegistry, currentlyRegisteredFactories);
+ SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
+ .createSRWritableRegistry(ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(),
+ txLookupRegistry, currentlyRegisteredFactories);
-
- testedTxController = new ConfigTransactionControllerImpl(
- txLookupRegistry, 1, null, 1,
- currentlyRegisteredFactories, transactionsMBeanServer,
- ManagementFactory.getPlatformMBeanServer(), false, writableRegistry);
+ testedTxController = new ConfigTransactionControllerImpl(txLookupRegistry, 1, null, 1,
+ currentlyRegisteredFactories, transactionsMBeanServer, ManagementFactory.getPlatformMBeanServer(),
+ false, writableRegistry);
TransactionModuleJMXRegistrator transactionModuleJMXRegistrator123 = testedTxController
.getTxModuleJMXRegistrator();
- transactionModuleJMXRegistrator123.registerMBean(
- new TestingRuntimeBean(), name1);
- transactionModuleJMXRegistrator123.registerMBean(
- new TestingRuntimeBean(), name2);
- transactionModuleJMXRegistrator123.registerMBean(
- new TestingRuntimeBean(), name3);
+ transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME1);
+ transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME2);
+ transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME3);
TransactionJMXRegistrator jmxRegistrator4 = baseJMXRegistrator
- .createTransactionJMXRegistrator(transactionName4);
- jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(
- new TestingRuntimeBean(), name4);
+ .createTransactionJMXRegistrator(TRANSACTION_NAME4);
+ jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(new TestingRuntimeBean(), NAME4);
}
@After
}
/**
- * Tests if lookup method returns all beans with defined transaction name
+ * Tests if lookup method returns all beans with defined transaction name.
*/
@Test
public void testLookupConfigBeans() {
Set<ObjectName> beans = testedTxController.lookupConfigBeans();
- assertEquals(Sets.newHashSet(name1, name2, name3), beans);
+ assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), beans);
}
@Test
public void testLookupConfigBeansWithModuleName() {
- Set<ObjectName> beans = testedTxController
- .lookupConfigBeans(moduleName124);
- assertEquals(Sets.newHashSet(name1, name2), beans);
+ Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124);
+ assertEquals(Sets.newHashSet(NAME1, NAME2), beans);
}
@Test
public void lookupConfigBeansWithModuleNameAndImplName() throws Exception {
- Set<ObjectName> beans = testedTxController.lookupConfigBeans(
- moduleName124, instanceName134);
- assertEquals(Sets.newHashSet(name1), beans);
+ Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124, INSTANCE_NAME134);
+ assertEquals(Sets.newHashSet(NAME1), beans);
}
-}
\ No newline at end of file
+}
/*
- * 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,
try {
configRegistryJMXRegistrator.registerToJMX(mockedRegistry);
fail();
- } catch (final Exception e) {
+ } catch (final InstanceAlreadyExistsException e) {
assertTrue(e instanceof InstanceAlreadyExistsException);
}
}
.createTransaction();
transaction.commit();
}
-
}
/*
- * 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,
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
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();
checkApspThreadCount(fixedNrOfThreads);
// check OSGi SR
List<RegistrationHolder> registrations =
- ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler).getRegistrations();
+ ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler)
+ .getRegistrations();
assertEquals(1, registrations.size());
RegistrationHolder record = registrations.get(0);
assertEquals(TestingThreadPoolIfc.class, record.clazz);
- assertEquals(ImmutableMap.of("name","ref"), record.props);
+ assertEquals(ImmutableMap.of("name", "ref"), record.props);
// switch reference to scheduled
ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
// check scheduled is used
checkApspThreadCount(scheduledNrOfThreads);
// check that dummy MXBean points to scheduled
- assertEquals(withoutTransactionName(scheduledTPTransactionON), serviceReferenceMXBean.getCurrentImplementation());
+ assertEquals(withoutTransactionName(scheduledTPTransactionON),
+ serviceReferenceMXBean.getCurrentImplementation());
// empty transaction
configRegistryClient.createTransaction().commit();
// get service mapping
- Map<String,Map<String,ObjectName>> serviceMapping = configRegistryClient.getServiceMapping();
- Map<String,Map<String,ObjectName>> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME,
- (Map<String, ObjectName>)ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON)));
+ Map<String, Map<String, ObjectName>> serviceMapping = configRegistryClient.getServiceMapping();
+ Map<String, Map<String, ObjectName>> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME,
+ (Map<String, ObjectName>) ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON)));
assertEquals(expectedMapping, serviceMapping);
// destroy all
ConfigTransactionJMXClient transaction4 = configRegistryClient.createTransaction();
Set<ObjectName> objectNames = transaction4.lookupConfigBeans();
- for(ObjectName on: objectNames) {
+ for (ObjectName on : objectNames) {
transaction4.destroyModule(on);
}
transaction4.commit();
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"));
}
/*
- * 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,
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;
@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);
doNothing().when(transactionStatus).checkCommitted();
doNothing().when(transactionStatus).checkNotCommitted();
- List<ModuleIdentifier> sortedModuleIdentifiers = tested
- .getSortedModuleIdentifiers();
- assertEquals(
- Arrays.asList(threadFactoryName, threadPoolName, apspName),
- sortedModuleIdentifiers);
-
+ List<ModuleIdentifier> sortedModuleIdentifiers = tested.getSortedModuleIdentifiers();
+ assertEquals(Arrays.asList(threadFactoryName, threadPoolName, apspName), sortedModuleIdentifiers);
}
/**
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);
}
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() {
doReturn(new ModuleIdentifier("fact", "instance")).when(mockedModule).getIdentifier();
return mockedModule;
}
-
}
/*
- * 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,
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
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());
}
-
}
/*
- * 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,
private static void assertRequireInterfaceAnnotationHasCorrectValue(final Class<?> clazz, final String methodName,
final Set<Class<?>> inspectedInterfaces, final Class<? extends AbstractServiceInterface> expectedValue) {
Method setter = findMethod(clazz, methodName);
- RequireInterface found = AttributeHolder
- .findRequireInterfaceAnnotation(setter, inspectedInterfaces);
+ RequireInterface found = AttributeHolder.findRequireInterfaceAnnotation(setter, inspectedInterfaces);
if (expectedValue == null) {
assertNull(found);
} else {
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;
private static void assertDescription(final Class<?> clazz, final String methodName,
final Set<Class<?>> exportedInterfaces, final String expectedValue) {
Method setter = findMethod(clazz, methodName);
- String found = AttributeHolder.findDescription(setter,
- exportedInterfaces);
+ String found = AttributeHolder.findDescription(setter, exportedInterfaces);
if (expectedValue == null) {
assertNull(found);
} else {
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")
@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 {
@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 {
@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 {
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"));
}
}
}
@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
@Test
public void testHasSomeMethodWithAnnotationsImpl() {
- HashSet<Class<?>> exportedInterfaces = Sets
- .<Class<?>> newHashSet(HasSomeMethodWithAnnotations.class);
+ HashSet<Class<?>> exportedInterfaces = Sets.<Class<?>>newHashSet(HasSomeMethodWithAnnotations.class);
assertRequireInterfaceAnnotationHasCorrectValue(HasSomeMethodWithAnnotationsImpl.class, setSomethingString,
exportedInterfaces, SubSI2.class);
/*
- * 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,
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;
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));
@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);
}
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));
} finally {
atomicBoolean.set(false);
}
-
}
-
}
/*
- * 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,
*/
package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import java.io.Closeable;
import java.util.AbstractMap;
-import java.util.Arrays;
-import java.util.Dictionary;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver {
- private Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
+ private final Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) {
this.factories = new HashMap<>(list.length);
for (ModuleFactory moduleFactory : list) {
String moduleName = moduleFactory.getImplementationName();
if (moduleName == null || moduleName.isEmpty()) {
- throw new IllegalStateException(
- "Invalid implementation name for " + moduleFactory);
+ throw new IllegalStateException("Invalid implementation name for " + moduleFactory);
}
Map.Entry<ModuleFactory, BundleContext> conflicting = factories.get(moduleName);
if (conflicting == null) {
}
}
- private static BundleContext mockBundleContext() {
- BundleContext bundleContext = Mockito.mock(BundleContext.class);
- ServiceRegistration<ModuleFactory> serviceRegistration = mock(ServiceRegistration.class);
- doNothing().when(serviceRegistration).unregister();
- doReturn(serviceRegistration).when(bundleContext).registerService(
- Matchers.any(String[].class), any(Closeable.class),
- any(Dictionary.class));
- return bundleContext;
- }
-
@Override
public Map<String, Map.Entry<ModuleFactory, BundleContext>> getAllFactories() {
return factories;
}
-
}
/*
- * 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,
@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());
/*
- * 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,
}
@Test
+ @SuppressWarnings("IllegalCatch")
public void testDuplicateFactories() throws Exception {
doReturn(f1).when(bundleContext).getService(s2);
try {
/*
- * 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,
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;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- return getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]);
- }
- }).when(bundle).loadClass(anyString());
+ doAnswer(invocation -> getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]))
+ .when(bundle).loadClass(anyString());
doReturn("mockBundle").when(bundle).toString();
doReturn(context).when(bundle).getBundleContext();
doReturn(reg).when(context).registerService(anyString(), anyObject(), any(Dictionary.class));
}
@Test
+ @SuppressWarnings("IllegalCatch")
public void testRegisterFactoryInstantiateEx() throws Exception {
try {
ModuleFactoryBundleTracker.registerFactory(WrongConstructorTestingFactory.class.getName(), bundle);
}
@Test
+ @SuppressWarnings("IllegalCatch")
public void testRegisterFactoryInstantiateExAccess() throws Exception {
try {
ModuleFactoryBundleTracker.registerFactory(NoAccessConstructorTestingFactory.class.getName(), bundle);
}
@Test
+ @SuppressWarnings("IllegalCatch")
public void testRegisterFactoryNotExtending() throws Exception {
try {
ModuleFactoryBundleTracker.registerFactory(NotExtendingTestingFactory.class.getName(), bundle);
}
@Test
+ @SuppressWarnings("IllegalCatch")
public void testRegisterFactoryNotExisting() throws Exception {
try {
ModuleFactoryBundleTracker.registerFactory("Unknown class", bundle);
}
@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());
}
}
- static class NotExtendingTestingFactory {}
+ static class NotExtendingTestingFactory {
+ }
static class NoAccessConstructorTestingFactory extends TestingFactory {
private NoAccessConstructorTestingFactory() {
}
@Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
throw new UnsupportedOperationException();
}
@Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
throw new UnsupportedOperationException();
}
@Override
- public boolean isModuleImplementingServiceInterface(final Class<? extends AbstractServiceInterface> serviceInterface) {
+ public boolean isModuleImplementingServiceInterface(
+ final Class<? extends AbstractServiceInterface> serviceInterface) {
throw new UnsupportedOperationException();
}
}
@Override
- public Set<? extends Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+ public Set<? extends Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext bundleContext) {
throw new UnsupportedOperationException();
}
}
/*
- * 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,
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;
@Mock
SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
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));
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();
/*
- * 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,
import org.opendaylight.controller.config.manager.impl.jmx.HierarchicalRuntimeBeanRegistrationImpl;
import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-public class RuntimeBeanRegistratorImplTest extends
- AbstractLockedPlatformMBeanServerTest {
- static final String module1 = "module1";
- static final String INSTANCE_NAME = "instanceName";
+public class RuntimeBeanRegistratorImplTest extends AbstractLockedPlatformMBeanServerTest {
+ private static final String MODULE1 = "module1";
+ private static final String INSTANCE_NAME = "instanceName";
String additionalKey = "key";
String additionalValue = "value";
- Map<String, String> additionalProperties = ImmutableMap.of(additionalKey,
- additionalValue);
+ Map<String, String> additionalProperties = ImmutableMap.of(additionalKey, additionalValue);
private BaseJMXRegistrator baseJMXRegistrator;
private RootRuntimeBeanRegistratorImpl tested;
- private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(
- module1, INSTANCE_NAME);
+ private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(MODULE1, INSTANCE_NAME);
@Before
public void setUp() {
- baseJMXRegistrator = new BaseJMXRegistrator(
- ManagementFactory.getPlatformMBeanServer());
- tested = baseJMXRegistrator
- .createRuntimeBeanRegistrator(moduleIdentifier);
+ baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
+ tested = baseJMXRegistrator.createRuntimeBeanRegistrator(moduleIdentifier);
}
@After
platformMBeanServer.getMBeanInfo(on);
fail();
} catch (final InstanceNotFoundException e) {
-
+ // FIXME: should it be empty?
}
}
createRoot();
}
- private HierarchicalRuntimeBeanRegistrationImpl createRoot()
- throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested
- .registerRoot(new TestingRuntimeBean());
+ private HierarchicalRuntimeBeanRegistrationImpl createRoot() throws Exception {
+ HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested.registerRoot(new TestingRuntimeBean());
- ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(module1,
- INSTANCE_NAME, Maps.<String, String> newHashMap());
+ ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME,
+ Maps.<String, String>newHashMap());
assertEquals(expectedON1, rootRegistration.getObjectName());
checkExists(rootRegistration.getObjectName());
}
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());
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()));
}
}
platformMBeanServer.unregisterMBean(rootRegistration.getObjectName());
rootRegistration.close();
}
-
}
/*
- * 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,
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;
}
- @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 {
@Test
public void testGetAllInterfaces() {
- Set<Class<?>> expected = Sets.<Class<?>> newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class,
- SubA.class, Identifiable.class, Module.class);
- assertEquals(expected,
- InterfacesHelper.getAllInterfaces(SubClass.class));
+ Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class, SubA.class,
+ Identifiable.class, Module.class);
+ assertEquals(expected, InterfacesHelper.getAllInterfaces(SubClass.class));
}
@Test
public void testGetServiceInterfaces() throws Exception {
assertEquals(Collections.<Class<?>>emptySet(), InterfacesHelper.getServiceInterfaces(SubClass.class));
- assertEquals(Sets.<Class<?>>newHashSet(Service.class, SubService.class), InterfacesHelper.getServiceInterfaces(SubClassWithService.class));
+ assertEquals(Sets.<Class<?>>newHashSet(Service.class, SubService.class),
+ InterfacesHelper.getServiceInterfaces(SubClassWithService.class));
}
@Test
@Test
public void testGetMXInterfaces() {
- Set<Class<?>> expected = Sets.<Class<?>> newHashSet(SuperBMXBean.class, SubA.class);
+ Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperBMXBean.class, SubA.class);
assertEquals(expected, InterfacesHelper.getMXInterfaces(SubClass.class));
}
@Test
- public void testGetAllAbstractServiceInterfaceClasses(){
+ public void testGetAllAbstractServiceInterfaceClasses() {
Class<? extends AbstractServiceInterface> clazz = TestingScheduledThreadPoolServiceInterface.class;
Set<Class<? extends AbstractServiceInterface>> input = new HashSet<>();
input.add(clazz);
- Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper.getAllAbstractServiceInterfaceClasses(input);
+ Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper
+ .getAllAbstractServiceInterfaceClasses(input);
Set<Class<?>> expected = ImmutableSet.of((Class<?>) TestingScheduledThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class
- );
+ TestingThreadPoolServiceInterface.class);
assertEquals(expected, result);
}
-
}
/*
- * 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,
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);
@Test
public void testAggregate() throws Exception {
-
}
-}
\ No newline at end of file
+}
/*
- * 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,
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";
String getSomeParam();
- void setSomeParam(String s);
+ void setSomeParam(String string);
// for reporting. this should be moved to runtime jmx bean
Integer getMaxNumberOfThreads();
-
}
/*
- * 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,
@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,
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;
}
-
}
/*
- * 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,
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;
* 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;
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;
@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
throw new RuntimeException(e);
}
}
- instance = new TestingParallelAPSPImpl(threadPoolInstance,
- someParam);
+ instance = new TestingParallelAPSPImpl(threadPoolInstance, someParam);
}
}
return instance;
public ModuleIdentifier getIdentifier() {
return identifier;
}
-
-
}
/*
- * 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,
@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);
}
@Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext context) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext context) {
return new HashSet<>();
}
/*
- * 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,
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;
@Before
public void setUp() {
super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- new TestingFixedThreadPoolModuleFactory(),
- new TestingParallelAPSPModuleFactory()));
+ new TestingFixedThreadPoolModuleFactory(), new TestingParallelAPSPModuleFactory()));
}
@After
public void testDependencies() throws Exception {
ObjectName apspON;
{
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
+ ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
// create fixed1
ObjectName threadPoolTransactionON = createFixed1(transaction,
TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS);
// create apsp-parallel
- ObjectName apspNameTransactionON = createParallelAPSP(transaction,
- threadPoolTransactionON);
- TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction
- .newMXBeanProxy(apspNameTransactionON, TestingParallelAPSPConfigMXBean.class);
+ ObjectName apspNameTransactionON = createParallelAPSP(transaction, threadPoolTransactionON);
+ TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction.newMXBeanProxy(apspNameTransactionON,
+ TestingParallelAPSPConfigMXBean.class);
parallelAPSPConfigProxy.setSomeParam("");// trigger validation
- // failure
+ // failure
try {
transaction.validateConfig();
fail();
} catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
- .getFailedValidations().entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
- .getValue().entrySet()) {
- assertThat(
- entry.getValue().getMessage(),
- containsString("Parameter 'SomeParam' is blank"));
+ for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+ .entrySet()) {
+ for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+ assertThat(entry.getValue().getMessage(), containsString("Parameter 'SomeParam' is blank"));
}
}
}
transaction.commit();
fail();
} catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
- .getFailedValidations().entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
- .getValue().entrySet()) {
+ for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+ .entrySet()) {
+ for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
String err = entry.getValue().getMessage();
- assertTrue("Unexpected error message: " + err,
- err.contains("Parameter 'SomeParam' is blank"));
+ assertTrue("Unexpected error message: " + err, err.contains("Parameter 'SomeParam' is blank"));
}
}
}
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
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();
-
}
}
/*
- * 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,
import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans.TestingScheduledRuntimeBean;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc,
- TestingScheduledThreadPoolIfc, Closeable {
+public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, TestingScheduledThreadPoolIfc, Closeable {
private static volatile int numberOfCloseMethodCalls = 0;
private final ScheduledThreadPoolExecutor executor;
private final RootRuntimeBeanRegistrator runtimeBeanRegistrator;
- public static final List<ScheduledThreadPoolExecutor> allExecutors = Lists
- .newLinkedList();
+ public static final List<ScheduledThreadPoolExecutor> ALLEXECUTORS = Lists.newLinkedList();
- public TestingScheduledThreadPoolImpl(
- final RootRuntimeBeanRegistrator runtimeBeanRegistrator, final int corePoolSize) {
+ public TestingScheduledThreadPoolImpl(final RootRuntimeBeanRegistrator runtimeBeanRegistrator,
+ final int corePoolSize) {
this.runtimeBeanRegistrator = runtimeBeanRegistrator;
executor = new ScheduledThreadPoolExecutor(corePoolSize);
- allExecutors.add(executor);
+ ALLEXECUTORS.add(executor);
HierarchicalRuntimeBeanRegistration hierarchicalRuntimeBeanRegistration = runtimeBeanRegistrator
.registerRoot(new TestingScheduledRuntimeBean());
- hierarchicalRuntimeBeanRegistration.register("a", "b",
- new TestingScheduledRuntimeBean());
+ hierarchicalRuntimeBeanRegistration.register("a", "b", new TestingScheduledRuntimeBean());
}
@Override
}
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;
}
-
}
/*
- * 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,
* 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
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;
}
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
}
@Override
+ @SuppressWarnings("IllegalCatch")
public Closeable getInstance() {
assertNotNull(runtimeBeanRegistrator);
if (instance == null) {
}
}
// close old threadpool and esp. unregister runtime beans
- instance = new TestingScheduledThreadPoolImpl(
- runtimeBeanRegistrator, threadCount);
+ instance = new TestingScheduledThreadPoolImpl(runtimeBeanRegistrator, threadCount);
}
}
return instance;
public ModuleIdentifier getIdentifier() {
return identifier;
}
-
-
}
/*
- * 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,
private static Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
(Class<? extends AbstractServiceInterface>) TestingScheduledThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class);
+ TestingThreadPoolServiceInterface.class);
@Override
public boolean isModuleImplementingServiceInterface(
}
@Override
- public Module createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME,
- instanceName), null, null);
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
+ return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null);
}
@Override
- public Module createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext)
- throws Exception {
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
TestingScheduledThreadPoolImpl oldInstance;
try {
oldInstance = (TestingScheduledThreadPoolImpl) old.getInstance();
- } catch (final ClassCastException e) {// happens after OSGi update
+ } catch (final ClassCastException e) {
+ // happens after OSGi update
oldInstance = null;
}
TestingScheduledThreadPoolModule configBean = new TestingScheduledThreadPoolModule(
- new ModuleIdentifier(NAME, instanceName), old.getInstance(),
- oldInstance);
+ new ModuleIdentifier(NAME, instanceName), old.getInstance(), oldInstance);
// copy attributes
configBean.setRecreate((Boolean) old.getAttribute("Recreate"));
return configBean;
}
@Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext bundleContext) {
return new HashSet<>();
}
public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
return ifc;
}
-
-
}
/*
- * 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;
/*
- * 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,
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() {
/*
- * 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,
/**
* TestingScheduledThreadPool exports 2 interfaces: <br>
- * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
+ * {@link org.opendaylight.controller.config.manager.testingservices
+ * .scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
* ,<br>
- * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME}
+ * {@link org.opendaylight.controller.config.manager
+ * .testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME}
* <br>
* <br>
* It also exports 2 runtime beans, one default and one with additional
*/
public class RuntimeBeanTest extends AbstractScheduledTest {
- ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(
- TestingScheduledThreadPoolModuleFactory.NAME, scheduled1,
- Maps.<String, String> newHashMap());
+ ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
+ SCHEDULED1, Maps.<String, String>newHashMap());
// additional runtime bean
- ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(
- TestingScheduledThreadPoolModuleFactory.NAME, scheduled1,
- ImmutableMap.of("a", "b"));
+ ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
+ SCHEDULED1, ImmutableMap.of("a", "b"));
- List<ObjectName> allObjectNames = Lists.newArrayList(ifc1runtimeON1,
- ifc1runtimeON2);
+ List<ObjectName> allObjectNames = Lists.newArrayList(ifc1runtimeON1, ifc1runtimeON2);
- private ObjectName createScheduled() throws InstanceAlreadyExistsException,
- ConflictingVersionException, ValidationException {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
+ private ObjectName createScheduled()
+ throws InstanceAlreadyExistsException, ConflictingVersionException, ValidationException {
+ ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
// create using TestingThreadPoolIfc:
- ObjectName createdConfigBean = transaction.createModule(
- TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+ ObjectName createdConfigBean = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
+ SCHEDULED1);
// commit
transaction.commit();
return createdConfigBean;
@Test
public void testLookup() throws Exception {
createScheduled();
- assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2),
- configRegistryClient.lookupRuntimeBeans());
+ assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2), configRegistryClient.lookupRuntimeBeans());
}
@Test
public void testReuse() throws Exception {
ObjectName createdConfigBean = createScheduled();
// empty transaction
- CommitStatus commitInfo = configRegistryClient.createTransaction()
- .commit();
+ CommitStatus commitInfo = configRegistryClient.createTransaction().commit();
// check that it was reused
- ObjectName readableConfigBean = ObjectNameUtil
- .withoutTransactionName(createdConfigBean);
- List<ObjectName> newInstances = Collections.<ObjectName> emptyList();
- List<ObjectName> reusedInstances = Lists
- .newArrayList(readableConfigBean);
- List<ObjectName> recreatedInstaces = Collections
- .<ObjectName> emptyList();
- assertEquals(new CommitStatus(newInstances, reusedInstances,
- recreatedInstaces), commitInfo);
+ ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
+ List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
+ List<ObjectName> reusedInstances = Lists.newArrayList(readableConfigBean);
+ List<ObjectName> recreatedInstaces = Collections.<ObjectName>emptyList();
+ assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
checkRuntimeBeans();
}
public void testRecreate() throws Exception {
ObjectName createdConfigBean = createScheduled();
// empty transaction
- ConfigTransactionJMXClient configTransaction = configRegistryClient
- .createTransaction();
- ObjectName scheduledWritableON = configTransaction.lookupConfigBean(
- TestingScheduledThreadPoolModuleFactory.NAME, scheduled1);
+ ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
+ ObjectName scheduledWritableON = configTransaction
+ .lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
TestingScheduledThreadPoolConfigBeanMXBean scheduledWritableProxy = configTransaction
.newMXBeanProxy(scheduledWritableON, TestingScheduledThreadPoolConfigBeanMXBean.class);
scheduledWritableProxy.setRecreate(true);
CommitStatus commitInfo = configTransaction.commit();
// check that it was recreated
- ObjectName readableConfigBean = ObjectNameUtil
- .withoutTransactionName(createdConfigBean);
- List<ObjectName> newInstances = Collections.<ObjectName> emptyList();
- List<ObjectName> reusedInstances = Collections.<ObjectName> emptyList();
- List<ObjectName> recreatedInstaces = Lists
- .newArrayList(readableConfigBean);
- assertEquals(new CommitStatus(newInstances, reusedInstances,
- recreatedInstaces), commitInfo);
+ ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
+ List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
+ List<ObjectName> reusedInstances = Collections.<ObjectName>emptyList();
+ List<ObjectName> recreatedInstaces = Lists.newArrayList(readableConfigBean);
+ assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
checkRuntimeBeans();
}
@Test
public void testDestroy_shouldUnregisterRuntimeBeans() throws Exception {
ObjectName createdConfigBean = createScheduled();
- ConfigTransactionJMXClient configTransaction = configRegistryClient
- .createTransaction();
- configTransaction.destroyModule(ObjectNameUtil
- .createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean));
+ ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
+ configTransaction.destroyModule(
+ ObjectNameUtil.createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean));
configTransaction.commit();
for (ObjectName on : allObjectNames) {
checkRuntimeBeanDoesNotExist(on);
}
}
-
}
/*
- * 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,
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));
}
}
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();
@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();
/*
- * 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,
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 {
}
/*
- * 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,
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";
}
/*
- * 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,
private final String uniqueName;
public static void cleanUp() {
- for (ExecutorService executorService : allExecutors) {
+ for (ExecutorService executorService : ALL_EXECUTORS) {
executorService.shutdown();
}
- allExecutors.clear();
+ ALL_EXECUTORS.clear();
}
// for verification purposes:
- public static final List<ThreadPoolExecutor> allExecutors = Collections
+ public static final List<ThreadPoolExecutor> ALL_EXECUTORS = Collections
.synchronizedList(Lists.<ThreadPoolExecutor>newLinkedList());
public TestingFixedThreadPool(final int threadCount, final String uniqueName) {
this.uniqueName = uniqueName;
executorService = (ThreadPoolExecutor) Executors
.newFixedThreadPool(threadCount);
- allExecutors.add(executorService);
+ ALL_EXECUTORS.add(executorService);
}
@Override
@Override
public void close() throws IOException {
executorService.shutdown();
- allExecutors.remove(executorService);
+ ALL_EXECUTORS.remove(executorService);
}
checkArgument(activeCount > 0);
executorService.setMaximumPoolSize(activeCount);
}
-
}
/*
- * 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,
this.oldInstance = oldInstance;
}
-
// attributes
@Override
public void setThreadCount(final int threadCount) {
}
@Override
+ @SuppressWarnings("IllegalCatch")
public Closeable getInstance() {
if (instance == null) {
if (isReusable() && triggerNewInstanceCreation == false) { // simulate
/*
- * 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,
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory implements ModuleFactory {
+public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory
+ implements ModuleFactory {
public static final String NAME = "fixed";
- private static final Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
+ private static final Set<Class<? extends AbstractServiceInterface>> IFC = ImmutableSet.of(
(Class<? extends AbstractServiceInterface>) ModifiableThreadPoolServiceInterface.class,
TestingThreadPoolServiceInterface.class);
@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;
// 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;
}
@Override
public boolean isModuleImplementingServiceInterface(
final Class<? extends AbstractServiceInterface> serviceInterface) {
- return ifc.contains(serviceInterface);
+ return IFC.contains(serviceInterface);
}
@Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
+ public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
+ final BundleContext bundleContext) {
return new HashSet<>();
}
@Override
public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- return ifc;
+ return IFC;
}
}
/*
- * 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,
*/
/**
* 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;
/*
- * 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,
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;
super.initConfigTransactionManagerImpl(mockedResolver);
}
-
@Test
public void testCreateAndDestroyBeanInSameTransaction() throws Exception {
{
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());
}
}
/*
- * 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,
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;
* dependencies.
*/
public class SimpleConfigurationTest extends AbstractConfigTest {
- private static final int numberOfThreads = 5;
- private final int numberOfThreads2 = 10;
- private static final String fixed1 = "fixed1";
- private static final List<ObjectName> emptyONs = Collections
- .<ObjectName> emptyList();
- private static final ObjectName platformFixed1ON = ObjectNameUtil
- .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, fixed1);
- private static final List<ObjectName> fixed1List = Arrays
- .asList(platformFixed1ON);
+ private static final int NUMBER_OF_THREADS = 5;
+ private static final int NUMBER_OF_THREADS2 = 10;
+ private static final String FIXED1 = "fixed1";
+ private static final List<ObjectName> EMPTYO_NS = Collections.<ObjectName>emptyList();
+ private static final ObjectName PLATFORM_FIXED1ON = ObjectNameUtil
+ .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
+ private static final List<ObjectName> FIXED1_LIST = Arrays.asList(PLATFORM_FIXED1ON);
@Before
public void setUp() {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- new TestingFixedThreadPoolModuleFactory()));
+ super.initConfigTransactionManagerImpl(
+ new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory()));
}
@After
}
private ObjectName firstCommit() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
+ ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
ObjectName fixed1names = createFixedThreadPool(transaction);
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();
@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();
transaction.validateBean(fixed1names);
fail();
} catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
- .getFailedValidations().entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
- .getValue().entrySet()) {
- assertEquals(
- "Parameter 'threadCount' must be greater than 0",
- entry.getValue().getMessage());
+ for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+ .entrySet()) {
+ for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+ assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
}
}
}
transaction.validateConfig();
fail();
} catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
- .getFailedValidations().entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
- .getValue().entrySet()) {
- assertEquals(
- "Parameter 'threadCount' must be greater than 0",
- entry.getValue().getMessage());
+ for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+ .entrySet()) {
+ for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+ assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
}
}
}
try {
transaction.commit();
} catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e
- .getFailedValidations().entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception
- .getValue().entrySet()) {
- assertEquals(
- "Parameter 'threadCount' must be greater than 0",
- entry.getValue().getMessage());
+ for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
+ .entrySet()) {
+ for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
+ assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
}
}
}
@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);
}
// 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);
}
}
// 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
// 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();
try {
platformMBeanServer.getMBeanInfo(transaction.getObjectName());
fail();
- }catch(final InstanceNotFoundException e){
- assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction", e.getMessage());
+ } catch (final InstanceNotFoundException e) {
+ assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction",
+ e.getMessage());
}
}
@Test
public void testOptimisticLock_ConfigTransactionClient() throws Exception {
- ConfigTransactionJMXClient transaction1 = configRegistryClient
- .createTransaction();
- ConfigTransactionJMXClient transaction2 = configRegistryClient
- .createTransaction();
+ ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
+ ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
transaction2.assertVersion(0, 2);
transaction2.commit();
try {
transaction1.commit();
fail();
} catch (final ConflictingVersionException e) {
- assertEquals(
- "Optimistic lock failed. Expected parent version 2, was 0",
- e.getMessage());
+ assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
}
}
@Test
public void testOptimisticLock_ConfigRegistry() throws Exception {
- ConfigTransactionJMXClient transaction1 = configRegistryClient
- .createTransaction();
- ConfigTransactionJMXClient transaction2 = configRegistryClient
- .createTransaction();
+ ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
+ ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
transaction2.assertVersion(0, 2);
transaction2.commit();
try {
configRegistryClient.commitConfig(transaction1.getObjectName());
fail();
} catch (final ConflictingVersionException e) {
- assertEquals(
- "Optimistic lock failed. Expected parent version 2, was 0",
- e.getMessage());
+ assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
}
}
-
@Test
public void testQNames() {
Set<String> availableModuleFactoryQNames = configRegistryClient.getAvailableModuleFactoryQNames();
assertEquals(Sets.newHashSet(expected), availableModuleFactoryQNames);
}
-
}