@ConstructorProperties(QNAME_ATTR_NAME)
public IdentityAttributeRef(String qNameOfIdentity) {
- if (qNameOfIdentity == null)
+ if (qNameOfIdentity == null) {
throw new NullPointerException("Parameter " + QNAME_ATTR_NAME + " is null");
+ }
this.qNameOfIdentity = qNameOfIdentity;
}
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof IdentityAttributeRef)) return false;
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof IdentityAttributeRef)) {
+ return false;
+ }
IdentityAttributeRef that = (IdentityAttributeRef) o;
- if (!qNameOfIdentity.equals(that.qNameOfIdentity)) return false;
+ if (!qNameOfIdentity.equals(that.qNameOfIdentity)) {
+ return false;
+ }
return true;
}
private final String attributeName;
public JmxAttribute(String attributeName) {
- if (attributeName == null)
+ if (attributeName == null) {
throw new NullPointerException("Parameter 'attributeName' is null");
+ }
this.attributeName = attributeName;
}
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (o == null || getClass() != o.getClass())
+ }
+ if (o == null || getClass() != o.getClass()) {
return false;
+ }
JmxAttribute that = (JmxAttribute) o;
if (attributeName != null ? !attributeName.equals(that.attributeName)
- : that.attributeName != null)
+ : that.attributeName != null) {
return false;
+ }
return true;
}
private final String factoryName, instanceName;
public ModuleIdentifier(String factoryName, String instanceName) {
- if (factoryName == null)
- throw new IllegalArgumentException(
- "Parameter 'factoryName' is null");
- if (instanceName == null)
- throw new IllegalArgumentException(
- "Parameter 'instanceName' is null");
+ if (factoryName == null) {
+ throw new IllegalArgumentException("Parameter 'factoryName' is null");
+ }
+ if (instanceName == null) {
+ throw new IllegalArgumentException("Parameter 'instanceName' is null");
+ }
this.factoryName = factoryName;
this.instanceName = instanceName;
}
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (o == null || getClass() != o.getClass())
+ }
+ if (o == null || getClass() != o.getClass()) {
return false;
+ }
ModuleIdentifier that = (ModuleIdentifier) o;
- if (!factoryName.equals(that.factoryName))
+ if (!factoryName.equals(that.factoryName)) {
return false;
- if (!instanceName.equals(that.instanceName))
+ }
+ if (!instanceName.equals(that.instanceName)) {
return false;
+ }
return true;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
ExceptionMessageWithStackTrace other = (ExceptionMessageWithStackTrace) obj;
if (message == null) {
- if (other.message != null)
+ if (other.message != null) {
return false;
- } else if (!message.equals(other.message))
+ }
+ } else if (!message.equals(other.message)) {
return false;
+ }
if (stackTrace == null) {
- if (other.stackTrace != null)
+ if (other.stackTrace != null) {
return false;
- } else if (!stackTrace.equals(other.stackTrace))
+ }
+ } else if (!stackTrace.equals(other.stackTrace)) {
return false;
+ }
return true;
}
*/
package org.opendaylight.controller.config.api.jmx;
+import javax.annotation.concurrent.Immutable;
+import javax.management.ObjectName;
import java.beans.ConstructorProperties;
import java.util.Collections;
import java.util.List;
-import javax.annotation.concurrent.Immutable;
-import javax.management.ObjectName;
-
@Immutable
public class CommitStatus {
private final List<ObjectName> newInstances, reusedInstances,
recreatedInstances;
/**
- *
- * @param newInstances
- * newly created instances
- * @param reusedInstances
- * reused instances
- * @param recreatedInstances
- * recreated instances
+ * @param newInstances newly created instances
+ * @param reusedInstances reused instances
+ * @param recreatedInstances recreated instances
*/
- @ConstructorProperties({ "newInstances", "reusedInstances",
- "recreatedInstances" })
+ @ConstructorProperties({"newInstances", "reusedInstances",
+ "recreatedInstances"})
public CommitStatus(List<ObjectName> newInstances,
- List<ObjectName> reusedInstances,
- List<ObjectName> recreatedInstances) {
+ List<ObjectName> reusedInstances,
+ List<ObjectName> recreatedInstances) {
this.newInstances = Collections.unmodifiableList(newInstances);
this.reusedInstances = Collections.unmodifiableList(reusedInstances);
this.recreatedInstances = Collections
}
/**
- *
* @return list of objectNames representing newly created instances
*/
public List<ObjectName> getNewInstances() {
}
/**
- *
* @return list of objectNames representing reused instances
*/
public List<ObjectName> getReusedInstances() {
}
/**
- *
* @return list of objectNames representing recreated instances
*/
public List<ObjectName> getRecreatedInstances() {
result = prime
* result
+ ((recreatedInstances == null) ? 0 : recreatedInstances
- .hashCode());
+ .hashCode());
result = prime * result
+ ((reusedInstances == null) ? 0 : reusedInstances.hashCode());
return result;
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
CommitStatus other = (CommitStatus) obj;
if (newInstances == null) {
- if (other.newInstances != null)
+ if (other.newInstances != null) {
return false;
- } else if (!newInstances.equals(other.newInstances))
+ }
+ } else if (!newInstances.equals(other.newInstances)) {
return false;
+ }
if (recreatedInstances == null) {
- if (other.recreatedInstances != null)
+ if (other.recreatedInstances != null) {
return false;
- } else if (!recreatedInstances.equals(other.recreatedInstances))
+ }
+ } else if (!recreatedInstances.equals(other.recreatedInstances)) {
return false;
+ }
if (reusedInstances == null) {
- if (other.reusedInstances != null)
+ if (other.reusedInstances != null) {
return false;
- } else if (!reusedInstances.equals(other.reusedInstances))
+ }
+ } else if (!reusedInstances.equals(other.reusedInstances)) {
return false;
+ }
return true;
}
import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
import javax.annotation.concurrent.ThreadSafe;
+import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.Arrays;
import java.util.HashMap;
public static ObjectName createON(String on) {
try {
return new ObjectName(on);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ } catch (MalformedObjectNameException e) {
+ throw new IllegalArgumentException(e);
}
}
Hashtable<String, String> table = new Hashtable<>(attribs);
try {
return new ObjectName(domain, table);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ } catch (MalformedObjectNameException e) {
+ throw new IllegalArgumentException(e);
}
}
public static String getServiceQName(ObjectName objectName) {
checkType(objectName, TYPE_SERVICE_REFERENCE);
String quoted = objectName.getKeyProperty(SERVICE_QNAME_KEY);
- String result = unquoteAndUnescape(objectName, quoted);
- return result;
+ return unquoteAndUnescape(objectName, quoted);
}
// ObjectName supports quotation and ignores tokens like =, but fails to ignore ? sign.
}
}
- public static void checkTypeOneOf(ObjectName objectName, String ... types) {
- for(String type: types) {
+ public static void checkTypeOneOf(ObjectName objectName, String... types) {
+ for (String type : types) {
if (type.equals(objectName.getKeyProperty(TYPE_KEY))) {
return;
}
public static ObjectName createModulePattern(String moduleName,
String instanceName) {
- if (moduleName == null)
+ if (moduleName == null) {
moduleName = "*";
- if (instanceName == null)
+ }
+ if (instanceName == null) {
instanceName = "*";
+ }
// do not return object names containing transaction name
ObjectName namePattern = ObjectNameUtil
.createON(ObjectNameUtil.ON_DOMAIN + ":"
String expectedType) {
checkType(objectName, expectedType);
String factoryName = getFactoryName(objectName);
- if (factoryName == null)
+ if (factoryName == null) {
throw new IllegalArgumentException(
"ObjectName does not contain module name");
+ }
String instanceName = getInstanceName(objectName);
- if (instanceName == null)
+ if (instanceName == null) {
throw new IllegalArgumentException(
"ObjectName does not contain instance name");
+ }
return new ModuleIdentifier(factoryName, instanceName);
}
*/
package org.opendaylight.controller.config.api.jmx.constants;
+import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
public class ConfigRegistryConstants {
public static final ObjectName OBJECT_NAME = createONWithDomainAndType(TYPE_CONFIG_REGISTRY);
- public static String GET_AVAILABLE_MODULE_NAMES_ATTRIBUT_NAME = "AvailableModuleNames";
+ public static final String GET_AVAILABLE_MODULE_NAMES_ATTRIBUT_NAME = "AvailableModuleNames";
public static ObjectName createONWithDomainAndType(String type) {
return createON(ON_DOMAIN, TYPE_KEY, type);
public static ObjectName createON(String name, String key, String value) {
try {
return new ObjectName(name, key, value);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ } catch (MalformedObjectNameException e) {
+ throw new IllegalArgumentException(e);
}
}
private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
@GuardedBy("this") // switched in every 2ndPC
- private CloseableServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
+ private CloseableServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
// constructor
public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
- MBeanServer configMBeanServer, CodecRegistry codecRegistry) {
+ MBeanServer configMBeanServer, CodecRegistry codecRegistry) {
this(resolver, configMBeanServer,
new BaseJMXRegistrator(configMBeanServer), codecRegistry);
}
// constructor
public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
- MBeanServer configMBeanServer,
- BaseJMXRegistrator baseJMXRegistrator, CodecRegistry codecRegistry) {
+ MBeanServer configMBeanServer,
+ BaseJMXRegistrator baseJMXRegistrator, CodecRegistry codecRegistry) {
this.resolver = resolver;
- this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
+ beanToOsgiServiceManager = new BeanToOsgiServiceManager();
this.configMBeanServer = configMBeanServer;
this.baseJMXRegistrator = baseJMXRegistrator;
this.codecRegistry = codecRegistry;
- this.registryMBeanServer = MBeanServerFactory
+ registryMBeanServer = MBeanServerFactory
.createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
- this.transactionsMBeanServer = MBeanServerFactory
+ transactionsMBeanServer = MBeanServerFactory
.createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
}
* {@inheritDoc}
*/
@Override
+ @SuppressWarnings("PMD.AvoidCatchingThrowable")
public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
throws ConflictingVersionException, ValidationException {
final String transactionName = ObjectNameUtil
return secondPhaseCommit(
configTransactionController, commitInfo);
} catch (Throwable t) { // some libs throw Errors: e.g.
- // javax.xml.ws.spi.FactoryFinder$ConfigurationError
+ // javax.xml.ws.spi.FactoryFinder$ConfigurationError
isHealthy = false;
logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
if (t instanceof RuntimeException) {
} else if (t instanceof Error) {
throw (Error) t;
} else {
- throw new RuntimeException(t);
+ throw new IllegalStateException(t);
}
}
}
for (DestroyedModule toBeDestroyed : commitInfo
.getDestroyedFromPreviousTransactions()) {
toBeDestroyed.close(); // closes instance (which should close
- // runtime jmx registrator),
+ // runtime jmx registrator),
// also closes osgi registration and ModuleJMXRegistrator
// registration
currentConfig.remove(toBeDestroyed.getIdentifier());
for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
.get(moduleIdentifier);
- if (entry == null)
+ if (entry == null) {
throw new NullPointerException("Module not found "
+ moduleIdentifier);
+ }
Module module = entry.getModule();
ObjectName primaryReadOnlyON = ObjectNameUtil
.createReadOnlyModuleON(moduleIdentifier);
// register to OSGi
if (osgiRegistration == null) {
ModuleFactory moduleFactory = entry.getModuleFactory();
- if(moduleFactory != null) {
+ if (moduleFactory != null) {
BundleContext bc = configTransactionController.
getModuleFactoryBundleContext(moduleFactory.getImplementationName());
osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
version = configTransactionController.getVersion();
// switch readable Service Reference Registry
- this.readableSRRegistry.close();
- this.readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
+ readableSRRegistry.close();
+ readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
return new CommitStatus(newInstances, reusedInstances,
*/
@Override
public Set<ObjectName> lookupConfigBeans(String moduleName,
- String instanceName) {
+ String instanceName) {
ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
instanceName);
return baseJMXRegistrator.queryNames(namePattern, null);
*/
@Override
public Set<ObjectName> lookupRuntimeBeans(String moduleName,
- String instanceName) {
- if (moduleName == null)
+ String instanceName) {
+ if (moduleName == null) {
moduleName = "*";
- if (instanceName == null)
+ }
+ if (instanceName == null) {
instanceName = "*";
+ }
ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
moduleName, instanceName);
return baseJMXRegistrator.queryNames(namePattern, null);
* {@link ConfigTransactionControllerInternal} instances, because platform
* MBeanServer transforms mbeans into another representation. Map is cleaned
* every time current transactions are requested.
- *
*/
@GuardedBy("ConfigRegistryImpl.this")
private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
* Can only be called from within synchronized method.
*/
public void add(String transactionName,
- ConfigTransactionControllerInternal transactionController) {
+ ConfigTransactionControllerInternal transactionController) {
Object oldValue = transactions.put(transactionName,
transactionController);
if (oldValue != null) {
public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
// first, remove closed transaction
for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
- .entrySet().iterator(); it.hasNext();) {
+ .entrySet().iterator(); it.hasNext(); ) {
Entry<String, ConfigTransactionControllerInternal> entry = it
.next();
if (entry.getValue().isClosed()) {
class ConfigTransactionControllerImpl implements
ConfigTransactionControllerInternal,
ConfigTransactionControllerImplMXBean,
- Identifiable<TransactionIdentifier>{
+ Identifiable<TransactionIdentifier> {
private static final Logger logger = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
private final ConfigTransactionLookupRegistry txLookupRegistry;
List<ModuleFactory> toBeAdded = new ArrayList<>();
List<ModuleFactory> toBeRemoved = new ArrayList<>();
- for(ModuleFactory moduleFactory: factoriesHolder.getModuleFactories()) {
- if (oldSet.contains(moduleFactory) == false){
+ for (ModuleFactory moduleFactory : factoriesHolder.getModuleFactories()) {
+ if (oldSet.contains(moduleFactory) == false) {
toBeAdded.add(moduleFactory);
}
}
- for(ModuleFactory moduleFactory: lastListOfFactories){
+ for (ModuleFactory moduleFactory : lastListOfFactories) {
if (newSet.contains(moduleFactory) == false) {
toBeRemoved.add(moduleFactory);
}
}
// remove modules belonging to removed factories
- for(ModuleFactory removedFactory: toBeRemoved){
+ for (ModuleFactory removedFactory : toBeRemoved) {
List<ModuleIdentifier> modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory);
for (ModuleIdentifier name : modulesOfRemovedFactory) {
destroyModule(name);
@Override
public synchronized ObjectName createModule(String factoryName,
- String instanceName) throws InstanceAlreadyExistsException {
+ String instanceName) throws InstanceAlreadyExistsException {
transactionStatus.checkNotCommitStarted();
transactionStatus.checkNotAborted();
throws InstanceAlreadyExistsException {
logger.debug("Adding module {} to transaction {}", moduleIdentifier, this);
- if (moduleIdentifier.equals(module.getIdentifier())==false) {
+ if (moduleIdentifier.equals(module.getIdentifier()) == false) {
throw new IllegalStateException("Incorrect name reported by module. Expected "
- + moduleIdentifier + ", got " + module.getIdentifier());
+ + moduleIdentifier + ", got " + module.getIdentifier());
}
- if (dependencyResolver.getIdentifier().equals(moduleIdentifier) == false ) {
+ if (dependencyResolver.getIdentifier().equals(moduleIdentifier) == false) {
throw new IllegalStateException("Incorrect name reported by dependency resolver. Expected "
+ moduleIdentifier + ", got " + dependencyResolver.getIdentifier());
}
// first remove refNames, it checks for objectname existence
try {
writableSRRegistry.removeServiceReferences(
- ObjectNameUtil.createTransactionModuleON(getTransactionName(),moduleIdentifier));
+ ObjectNameUtil.createTransactionModuleON(getTransactionName(), moduleIdentifier));
} catch (InstanceNotFoundException e) {
logger.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
throw new IllegalStateException("Possible code error: cannot find " + moduleIdentifier, e);
@Override
public synchronized void validateConfig() throws ValidationException {
- if (configBeanModificationDisabled.get())
+ if (configBeanModificationDisabled.get()) {
throw new IllegalStateException("Cannot start validation");
+ }
configBeanModificationDisabled.set(true);
try {
validate_noLocks();
logger.error("Commit failed on {} in transaction {}", name,
getTransactionIdentifier(), e);
internalAbort();
- throw new RuntimeException(
+ throw new IllegalStateException(
format("Error - getInstance() failed for %s in transaction %s",
name, getTransactionIdentifier()), e);
}
*/
package org.opendaylight.controller.config.manager.impl;
-import javax.annotation.Nullable;
-
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator
- .TransactionModuleJMXRegistration;
+import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator.TransactionModuleJMXRegistration;
import org.opendaylight.controller.config.spi.Module;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.opendaylight.yangtools.concepts.Identifiable;
+import javax.annotation.Nullable;
+
public class ModuleInternalTransactionalInfo implements Identifiable<ModuleIdentifier> {
private final ModuleIdentifier name;
private final Module module;
private final boolean isDefaultBean;
ModuleInternalTransactionalInfo(ModuleIdentifier name, Module module,
- ModuleFactory moduleFactory,
- ModuleInternalInfo maybeOldInternalInfo,
- TransactionModuleJMXRegistration transactionModuleJMXRegistration,
- boolean isDefaultBean) {
+ ModuleFactory moduleFactory,
+ ModuleInternalInfo maybeOldInternalInfo,
+ TransactionModuleJMXRegistration transactionModuleJMXRegistration,
+ boolean isDefaultBean) {
this.name = name;
this.module = module;
this.moduleFactory = moduleFactory;
@Nullable
public ModuleInternalInfo getOldInternalInfo() {
- if (maybeOldInternalInfo == null)
+ if (maybeOldInternalInfo == null) {
throw new NullPointerException();
+ }
return maybeOldInternalInfo;
}
this.serviceReferenceRegistrator = serviceReferenceRegistratorFactory.create();
- Map<String, Set<String /* QName */>> factoryNamesToQNames = new HashMap<>();
+ Map<String, Set<String /* QName */>> modifiableFactoryNamesToQNames = new HashMap<>();
Set<ServiceInterfaceAnnotation> allAnnotations = new HashSet<>();
Set<String /* qName */> allQNames = new HashSet<>();
for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
}
allAnnotations.addAll(siAnnotations);
allQNames.addAll(qNames);
- factoryNamesToQNames.put(entry.getKey(), Collections.unmodifiableSet(qNames));
+ modifiableFactoryNamesToQNames.put(entry.getKey(), Collections.unmodifiableSet(qNames));
}
- this.factoryNamesToQNames = Collections.unmodifiableMap(factoryNamesToQNames);
+ this.factoryNamesToQNames = Collections.unmodifiableMap(modifiableFactoryNamesToQNames);
this.allQNames = Collections.unmodifiableSet(allQNames);
// fill namespacesToAnnotations
- Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> namespacesToAnnotations =
+ Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> modifiableNamespacesToAnnotations =
new HashMap<>();
for (ServiceInterfaceAnnotation sia : allAnnotations) {
- Map<String, ServiceInterfaceAnnotation> ofNamespace = namespacesToAnnotations.get(sia.namespace());
+ Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations.get(sia.namespace());
if (ofNamespace == null) {
ofNamespace = new HashMap<>();
- namespacesToAnnotations.put(sia.namespace(), ofNamespace);
+ modifiableNamespacesToAnnotations.put(sia.namespace(), ofNamespace);
}
if (ofNamespace.containsKey(sia.localName())) {
logger.error("Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
- sia.namespace(), sia.localName(), namespacesToAnnotations);
+ sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
throw new IllegalArgumentException("Conflict between local names in " + sia.namespace() + " : " + sia.localName());
}
ofNamespace.put(sia.localName(), sia);
}
- this.namespacesToAnnotations = Collections.unmodifiableMap(namespacesToAnnotations);
+ this.namespacesToAnnotations = Collections.unmodifiableMap(modifiableNamespacesToAnnotations);
// copy refNames
logger.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
}
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (o == null || getClass() != o.getClass())
+ }
+ if (o == null || getClass() != o.getClass()) {
return false;
+ }
TransactionIdentifier that = (TransactionIdentifier) o;
- if (name != null ? !name.equals(that.name) : that.name != null)
+ if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
+ }
return true;
}
}
public synchronized void checkNotCommitStarted() {
- if (secondPhaseCommitStarted == true)
+ if (secondPhaseCommitStarted == true) {
throw new IllegalStateException("Commit was triggered");
+ }
}
public synchronized void checkCommitStarted() {
- if (secondPhaseCommitStarted == false)
+ if (secondPhaseCommitStarted == false) {
throw new IllegalStateException("Commit was not triggered");
+ }
}
public synchronized void checkNotAborted() {
- if (aborted == true)
+ if (aborted == true) {
throw new IllegalStateException("Configuration was aborted");
+ }
}
public synchronized void checkNotCommitted() {
* during validation. Tracks dependencies for ordering purposes.
*/
final class DependencyResolverImpl implements DependencyResolver,
- Comparable<DependencyResolverImpl> {
+ Comparable<DependencyResolverImpl> {
private static final Logger logger = LoggerFactory.getLogger(DependencyResolverImpl.class);
private final ModulesHolder modulesHolder;
throw new NullPointerException(
"Parameter 'expectedServiceInterface' is null");
}
- if (jmxAttribute == null)
+ if (jmxAttribute == null) {
throw new NullPointerException("Parameter 'jmxAttribute' is null");
+ }
JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
"is null, expected dependency implementing "
+ expectedServiceInterface, jmxAttribute);
-
// check that objectName belongs to this transaction - this should be
// stripped
// in DynamicWritableWrapper
//TODO: check for cycles
@Override
public <T> T resolveInstance(Class<T> expectedType, ObjectName dependentReadOnlyON,
- JmxAttribute jmxAttribute) {
+ JmxAttribute jmxAttribute) {
if (expectedType == null || dependentReadOnlyON == null || jmxAttribute == null) {
throw new IllegalArgumentException(format(
"Null parameters not allowed, got %s %s %s", expectedType,
throw new JmxAttributeValidationException(message, jmxAttribute);
}
try {
- T result = expectedType.cast(instance);
- return result;
+ return expectedType.cast(instance);
} catch (ClassCastException e) {
String message = format(
"Instance cannot be cast to expected type. Instance class is %s , "
IdentityCodec<?> identityCodec = codecRegistry.getIdentityCodec();
Class<? extends BaseIdentity> deserialized = identityCodec.deserialize(qName);
if (deserialized == null) {
- throw new RuntimeException("Unable to retrieve identity class for " + qName + ", null response from "
+ throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
+ codecRegistry);
}
if (expectedBaseClass.isAssignableFrom(deserialized)) {
public <T extends BaseIdentity> void validateIdentity(IdentityAttributeRef identityRef, Class<T> expectedBaseClass, JmxAttribute jmxAttribute) {
try {
resolveIdentity(identityRef, expectedBaseClass);
- } catch(Exception e) {
+ } catch (Exception e) {
throw JmxAttributeValidationException.wrap(e, jmxAttribute);
}
}
}
private static int getMaxDepth(DependencyResolverImpl impl,
- DependencyResolverManager manager,
- LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
+ DependencyResolverManager manager,
+ LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
int maxDepth = 0;
LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(
chainForDetectingCycles);
* requests (getAttribute, setAttribute, invoke) into the actual instance, but
* provides additional functionality - namely it disallows setting attribute on
* a read only wrapper.
- *
*/
abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
private static final Logger logger = LoggerFactory
protected final MBeanServer internalServer;
public AbstractDynamicWrapper(Module module, boolean writable,
- ModuleIdentifier moduleIdentifier,
- ObjectName thisWrapperObjectName, MBeanOperationInfo[] dOperations,
- MBeanServer internalServer, MBeanServer configMBeanServer) {
+ ModuleIdentifier moduleIdentifier,
+ ObjectName thisWrapperObjectName, MBeanOperationInfo[] dOperations,
+ MBeanServer internalServer, MBeanServer configMBeanServer) {
this.writable = writable;
this.module = module;
* case unregister the module and remove listener.
*/
private final NotificationListener registerActualModule(Module module,
- final ObjectName thisWrapperObjectName,
- final ObjectName objectNameInternal,
- final MBeanServer internalServer,
- final MBeanServer configMBeanServer) {
+ final ObjectName thisWrapperObjectName,
+ final ObjectName objectNameInternal,
+ final MBeanServer internalServer,
+ final MBeanServer configMBeanServer) {
try {
internalServer.registerMBean(module, objectNameInternal);
public void handleNotification(Notification n, Object handback) {
if (n instanceof MBeanServerNotification
&& n.getType()
- .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
+ .equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
if (((MBeanServerNotification) n).getMBeanName().equals(
thisWrapperObjectName)) {
try {
}
private static MBeanInfo generateMBeanInfo(String className, Module module,
- Map<String, AttributeHolder> attributeHolderMap,
- MBeanOperationInfo[] dOperations, Set<Class<?>> jmxInterfaces) {
+ Map<String, AttributeHolder> attributeHolderMap,
+ MBeanOperationInfo[] dOperations, Set<Class<?>> jmxInterfaces) {
String dDescription = findDescription(module.getClass(), jmxInterfaces);
MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[0];
// inspect all exported interfaces ending with MXBean, extract getters &
// setters into attribute holder
private static Map<String, AttributeHolder> buildMBeanInfo(Module module,
- boolean writable, ModuleIdentifier moduleIdentifier,
- Set<Class<?>> jmxInterfaces, MBeanServer internalServer,
- ObjectName internalObjectName) {
+ boolean writable, ModuleIdentifier moduleIdentifier,
+ Set<Class<?>> jmxInterfaces, MBeanServer internalServer,
+ ObjectName internalObjectName) {
// internal variables for describing MBean elements
Set<Method> methods = new HashSet<>();
}
AttributeHolder attributeHolder = new AttributeHolder(
attribName, module, attributeMap.get(attribName)
- .getType(), writable, ifc, description);
+ .getType(), writable, ifc, description);
attributeHolderMap.put(attribName, attributeHolder);
}
}
}
- if(isDependencyListAttr(attributeName, obj)) {
+ if (isDependencyListAttr(attributeName, obj)) {
obj = fixDependencyListAttribute(obj);
}
}
private Object fixDependencyListAttribute(Object attribute) {
- if(attribute.getClass().isArray() == false)
+ if (attribute.getClass().isArray() == false) {
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 == false)
+ if (on instanceof ObjectName == false) {
throw new IllegalArgumentException("Unexpected attribute type, should be an ObjectName, but was " + on.getClass());
+ }
on = fixObjectName((ObjectName) on);
Array.set(attribute, i, on);
}
private boolean isDependencyListAttr(String attributeName, Object attribute) {
- if (attributeHolderMap.containsKey(attributeName) == false)
+ if (attributeHolderMap.containsKey(attributeName) == false) {
return false;
+ }
AttributeHolder attributeHolder = attributeHolderMap.get(attributeName);
}
protected ObjectName fixObjectName(ObjectName on) {
- if (!ObjectNameUtil.ON_DOMAIN.equals(on.getDomain()))
+ if (!ObjectNameUtil.ON_DOMAIN.equals(on.getDomain())) {
throw new IllegalArgumentException("Wrong domain, expected "
+ ObjectNameUtil.ON_DOMAIN + " setter on " + on);
+ }
// if on contains transaction name, remove it
String transactionName = ObjectNameUtil.getTransactionName(on);
- if (transactionName != null)
+ if (transactionName != null) {
return ObjectNameUtil.withoutTransactionName(on);
- else
+ } else {
return on;
+ }
}
@Override
*/
package org.opendaylight.controller.config.manager.impl.dynamicmbean;
+import org.opendaylight.controller.config.api.annotations.Description;
+
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import org.opendaylight.controller.config.api.annotations.Description;
-
-class AnnotationsHelper {
+public class AnnotationsHelper {
/**
* Look for annotation specified by annotationType on method. First observe
}
public AttributeHolder(String name, Object object, String returnType,
- boolean writable,
- @Nullable RequireInterface requireInterfaceAnnotation,
- String description) {
+ boolean writable,
+ @Nullable RequireInterface requireInterfaceAnnotation,
+ String description) {
if (name == null) {
throw new NullPointerException();
}
/**
* @return annotation if setter sets ObjectName or ObjectName[], and is
- * annotated. Return null otherwise.
+ * annotated. Return null otherwise.
*/
RequireInterface getRequireInterfaceOrNull() {
return requireInterfaceAnnotation;
* @param setter
* @param jmxInterfaces
* @return empty string if no annotation is found, or list of descriptions
- * separated by newline
+ * separated by newline
*/
static String findDescription(Method setter, Set<Class<?>> jmxInterfaces) {
List<Description> descriptions = AnnotationsHelper
*
* @param setter
* @param inspectedInterfaces
- * @throws IllegalStateException
- * if more than one value is specified by found annotations
- * @throws IllegalArgumentException
- * if set of exported interfaces contains non interface type
* @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
*/
static RequireInterface findRequireInterfaceAnnotation(final Method setter,
- Set<Class<?>> inspectedInterfaces) {
+ Set<Class<?>> inspectedInterfaces) {
// only allow setX(ObjectName y) or setX(ObjectName[] y) or setX(List<ObjectName> y) to continue
- if (setter.getParameterTypes().length > 1)
+ if (setter.getParameterTypes().length > 1) {
return null;
- if(PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0]) == false)
+ }
+ if (PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0]) == false) {
return null;
+ }
List<RequireInterface> foundRequireInterfaces = AnnotationsHelper
.findMethodAnnotationInSuperClassesAndIfcs(setter, RequireInterface.class, inspectedInterfaces);
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import java.util.Map.Entry;
-import java.util.Set;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
-import java.util.Collections;
+import java.util.Map.Entry;
+import java.util.Set;
import java.util.TreeSet;
-import java.util.Collection;
-import java.util.ArrayList;
/**
* Hold sorted ConfigMBeanFactories by their module names. Check that module
* names are globally unique.
*/
public class HierarchicalConfigMBeanFactoriesHolder {
- private static final Logger logger = LoggerFactory
- .getLogger(HierarchicalConfigMBeanFactoriesHolder.class);
private final Map<String, Map.Entry<ModuleFactory, BundleContext>> moduleNamesToConfigBeanFactories;
private final Set<String> moduleNames;
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import java.io.Closeable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
import javax.management.JMX;
+import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
+import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.QueryExp;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.Closeable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
public class InternalJMXRegistrator implements Closeable {
private static final Logger logger = LoggerFactory
private final ObjectName on;
InternalJMXRegistration(InternalJMXRegistrator internalJMXRegistrator,
- ObjectName on) {
+ ObjectName on) {
this.internalJMXRegistrator = internalJMXRegistrator;
this.on = on;
}
private final List<InternalJMXRegistrator> children = new ArrayList<>();
public synchronized InternalJMXRegistration registerMBean(Object object,
- ObjectName on) throws InstanceAlreadyExistsException {
+ ObjectName on) throws InstanceAlreadyExistsException {
try {
configMBeanServer.registerMBean(object, on);
- } catch (InstanceAlreadyExistsException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
+ } catch (MBeanRegistrationException | NotCompliantMBeanException e) {
+ throw new IllegalStateException(e);
}
registeredObjectNames.add(on);
return new InternalJMXRegistration(this, on);
private synchronized void unregisterMBean(ObjectName on) {
// first check that on was registered using this instance
boolean removed = registeredObjectNames.remove(on);
- if (!removed)
- throw new IllegalStateException(
- "Cannot unregister - ObjectName not found in 'registeredObjectNames': "
- + on);
+ if (!removed) {
+ throw new IllegalStateException("Cannot unregister - ObjectName not found in 'registeredObjectNames': " + on);
+ }
try {
configMBeanServer.unregisterMBean(on);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ } catch (InstanceNotFoundException | MBeanRegistrationException e) {
+ throw new IllegalStateException(e);
}
}
}
public <T> T newMBeanProxy(ObjectName objectName, Class<T> interfaceClass,
- boolean notificationBroadcaster) {
+ boolean notificationBroadcaster) {
return JMX.newMBeanProxy(configMBeanServer, objectName, interfaceClass,
notificationBroadcaster);
}
}
public <T> T newMXBeanProxy(ObjectName objectName, Class<T> interfaceClass,
- boolean notificationBroadcaster) {
+ boolean notificationBroadcaster) {
return JMX.newMXBeanProxy(configMBeanServer, objectName,
interfaceClass, notificationBroadcaster);
}
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
ServiceReference that = (ServiceReference) o;
- if (!refName.equals(that.refName)) return false;
- if (!serviceInterfaceName.equals(that.serviceInterfaceName)) return false;
+ if (!refName.equals(that.refName)) {
+ return false;
+ }
+ if (!serviceInterfaceName.equals(that.serviceInterfaceName)) {
+ return false;
+ }
return true;
}
*/
package org.opendaylight.controller.config.manager.impl.jmx;
-import java.io.Closeable;
-import java.util.Set;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
import javax.management.QueryExp;
-
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator.InternalJMXRegistration;
+import java.io.Closeable;
+import java.util.Set;
/**
* Contains constraints on passed {@link ObjectName} parameters. Only allow (un)
private final String transactionName;
TransactionJMXRegistrator(InternalJMXRegistrator internalJMXRegistrator,
- String transactionName) {
+ String transactionName) {
this.childJMXRegistrator = internalJMXRegistrator.createChild();
this.transactionName = transactionName;
}
public TransactionJMXRegistration registerMBean(Object object, ObjectName on)
throws InstanceAlreadyExistsException {
- if (!transactionName.equals(ObjectNameUtil.getTransactionName(on)))
+ if (!transactionName.equals(ObjectNameUtil.getTransactionName(on))) {
throw new IllegalArgumentException(
"Transaction name mismatch between expected "
+ transactionName + " " + "and " + on);
+ }
ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_CONFIG_TRANSACTION);
return new TransactionJMXRegistration(
childJMXRegistrator.registerMBean(object, on));
if(factory == null) {
throw new NullPointerException("ServiceReference of class" + serviceReference.getClass() + "not found.");
}
- StringBuffer errors = new StringBuffer();
+
String moduleName = factory.getImplementationName();
if (moduleName == null || moduleName.isEmpty()) {
throw new IllegalStateException(
throw new NullPointerException("Bundle context of " + factory + " ModuleFactory not found.");
}
logger.debug("Reading factory {} {}", moduleName, factory);
- String error = null;
+
Map.Entry<ModuleFactory, BundleContext> conflicting = result.get(moduleName);
if (conflicting != null) {
- error = String
- .format("Module name is not unique. Found two conflicting factories with same name '%s': " +
- "\n\t%s\n\t%s\n", moduleName, conflicting.getKey(), factory);
-
- }
-
- if (error == null) {
+ String error = String
+ .format("Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
+ moduleName, conflicting.getKey(), factory);
+ logger.error(error);
+ throw new IllegalArgumentException(error);
+ } else {
result.put(moduleName, new AbstractMap.SimpleImmutableEntry<>(factory,
serviceReference.getBundle().getBundleContext()));
- } else {
- errors.append(error);
- }
- if (errors.length() > 0) {
- throw new IllegalArgumentException(errors.toString());
}
}
return result;
private RuntimeGeneratedMappingServiceActivator mappingServiceActivator;
@Override
- public void start(BundleContext context) throws Exception {
+ public void start(BundleContext context) {
// track bundles containing YangModuleInfo
ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker();
try {
configRegistryJMXRegistrator.registerToJMX(configRegistry);
} catch (InstanceAlreadyExistsException e) {
- throw new RuntimeException("Config Registry was already registered to JMX", e);
+ throw new IllegalStateException("Config Registry was already registered to JMX", e);
}
ServiceTracker<ModuleFactory, Object> serviceTracker = new ServiceTracker<>(context, ModuleFactory.class,
}
@Override
- public void stop(BundleContext context) throws Exception {
+ public void stop(BundleContext context) {
try {
configRegistry.close();
} catch (Exception e) {
ftlFile.getFtlTempleteLocation());
try {
template.process(ftlFile, writer);
- } catch (Throwable e) {
+ } catch (Exception e) {
throw new IllegalStateException(
"Template error while generating " + ftlFile, e);
}
boolean providedServiceWasSet = false;
for (UnknownSchemaNode unknownNode : id.getUnknownSchemaNodes()) {
// TODO: test this
- if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
- // no op: 0 or more provided identities are allowed
- } else if (ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
+ boolean unknownNodeIsProvidedServiceExtension = ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType());
+ // true => no op: 0 or more provided identities are allowed
+
+ if (ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
// 0..1 allowed
checkState(
providedServiceWasSet == false,
format("More than one language extension %s is not allowed here: %s",
ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME, id));
providedServiceWasSet = true;
- } else {
+ } else if (unknownNodeIsProvidedServiceExtension == false) {
throw new IllegalStateException("Unexpected language extension " + unknownNode.getNodeType());
}
}
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@Override
public CompositeType getOpenType() {
- String description = getNullableDescription() == null ? getAttributeYangName()
- : getNullableDescription();
- final String[] itemNames = new String[yangNameToAttributeMap.keySet()
- .size()];
- String[] itemDescriptions = itemNames;
- FunctionImpl functionImpl = new FunctionImpl(itemNames);
+ String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
+
+ FunctionImpl functionImpl = new FunctionImpl();
Map<String, AttributeIfc> jmxPropertiesToTypesMap = getJmxPropertiesToTypesMap();
OpenType<?>[] itemTypes = Collections2.transform(
jmxPropertiesToTypesMap.entrySet(), functionImpl).toArray(
new OpenType<?>[] {});
+ String[] itemNames = functionImpl.getItemNames();
try {
// TODO add package name to create fully qualified name for this
// type
CompositeType compositeType = new CompositeType(
getUpperCaseCammelCase(), description, itemNames,
- itemDescriptions, itemTypes);
+ itemNames, itemTypes);
return compositeType;
} catch (OpenDataException e) {
throw new RuntimeException("Unable to create CompositeType for "
return packageName;
}
- private static final class FunctionImpl implements
- Function<Entry<String, AttributeIfc>, OpenType<?>> {
- private final String[] itemNames;
- int i = 0;
+}
- private FunctionImpl(String[] itemNames) {
- this.itemNames = itemNames;
- }
+class FunctionImpl implements
+ Function<Entry<String, AttributeIfc>, OpenType<?>> {
+ private final List<String> itemNames = new ArrayList<>();
- @Override
- public OpenType<?> apply(Entry<String, AttributeIfc> input) {
- AttributeIfc innerType = input.getValue();
- itemNames[i++] = input.getKey();
- return innerType.getOpenType();
- }
+ @Override
+ public OpenType<?> apply(Entry<String, AttributeIfc> input) {
+ AttributeIfc innerType = input.getValue();
+ itemNames.add(input.getKey());
+ return innerType.getOpenType();
+ }
+
+ public String[] getItemNames(){
+ return itemNames.toArray(new String[itemNames.size()]);
}
}