@Override
public String toString() {
- final StringBuffer sb = new StringBuffer("IdentityAttributeRef{");
+ final StringBuilder sb = new StringBuilder("IdentityAttributeRef{");
sb.append("qNameOfIdentity='").append(qNameOfIdentity).append('\'');
sb.append('}');
return sb.toString();
*/
@ThreadSafe
public class ObjectNameUtil {
+ private ObjectNameUtil() {
+ }
public static final String ON_DOMAIN = ConfigRegistryConstants.ON_DOMAIN;
public static final String MODULE_FACTORY_NAME_KEY = "moduleFactoryName";
}
public static Map<String, String> getAdditionalProperties(ObjectName on) {
- Hashtable<String, String> keyPropertyList = on.getKeyPropertyList();
+ Map<String, String> keyPropertyList = on.getKeyPropertyList();
Map<String, String> result = new HashMap<>();
for (Entry<String, String> entry : keyPropertyList.entrySet()) {
result.put(entry.getKey(), entry.getValue());
public static ObjectName createModulePattern(String moduleName,
String instanceName) {
- moduleName = moduleName == null ? ON_WILDCARD : moduleName;
- instanceName = instanceName == null ? ON_WILDCARD : instanceName;
+ String finalModuleName = moduleName == null ? ON_WILDCARD : moduleName;
+ String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
// do not return object names containing transaction name
ObjectName namePattern = ObjectNameUtil
+ ObjectNameUtil.TYPE_KEY + "="
+ ObjectNameUtil.TYPE_MODULE + ","
+ ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "="
- + moduleName + "," + ""
- + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + instanceName);
+ + finalModuleName + "," + ""
+ + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + finalInstanceName);
return namePattern;
}
public static ObjectName createModulePattern(String ifcName,
String instanceName, String transactionName) {
- ifcName = ifcName == null ? ON_WILDCARD : ifcName;
- instanceName = instanceName == null ? ON_WILDCARD : instanceName;
- transactionName = transactionName == null ? ON_WILDCARD : transactionName;
+ String finalIfcName = ifcName == null ? ON_WILDCARD : ifcName;
+ String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
+ String finalTransactionName = transactionName == null ? ON_WILDCARD : transactionName;
return ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
+ ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + ifcName + "," + ObjectNameUtil.INSTANCE_NAME_KEY + "="
- + instanceName + "," + ObjectNameUtil.TRANSACTION_NAME_KEY
- + "=" + transactionName);
+ + "=" + finalIfcName + "," + ObjectNameUtil.INSTANCE_NAME_KEY + "="
+ + finalInstanceName + "," + ObjectNameUtil.TRANSACTION_NAME_KEY
+ + "=" + finalTransactionName);
}
public static ObjectName createRuntimeBeanPattern(String moduleName,
String instanceName) {
- moduleName = moduleName == null ? ON_WILDCARD : moduleName;
- instanceName = instanceName == null ? ON_WILDCARD : instanceName;
+ String finalModuleName = moduleName == null ? ON_WILDCARD : moduleName;
+ String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
return ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN + ":"
+ ObjectNameUtil.TYPE_KEY + "="
+ ObjectNameUtil.TYPE_RUNTIME_BEAN + ","
- + ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "=" + moduleName
- + "," + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + instanceName
+ + ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "=" + finalModuleName
+ + "," + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + finalInstanceName
+ ",*");
}
public class ConfigRegistryConstants {
+ private ConfigRegistryConstants() {
+ }
+
public static final String TYPE_CONFIG_REGISTRY = "ConfigRegistry";
public static final String ON_DOMAIN = "org.opendaylight.controller";
*/
@ThreadSafe
public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
- private static final Logger logger = LoggerFactory.getLogger(ConfigRegistryImpl.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRegistryImpl.class);
private final ModuleFactoriesResolver resolver;
private final MBeanServer configMBeanServer;
for (ModuleInternalInfo moduleInternalInfo : currentConfig.getEntries()) {
String name = moduleInternalInfo.getModuleFactory().getImplementationName();
if (allCurrentFactories.containsKey(name) == false) {
- logger.trace("Factory {} not found in SR, using reference from previous commit", name);
+ LOGGER.trace("Factory {} not found in SR, using reference from previous commit", name);
allCurrentFactories.put(name,
Maps.immutableEntry(moduleInternalInfo.getModuleFactory(), moduleInternalInfo.getBundleContext()));
}
throws ConflictingVersionException, ValidationException {
final String transactionName = ObjectNameUtil
.getTransactionName(transactionControllerON);
- logger.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
+ LOGGER.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
// find ConfigTransactionController
Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder.getCurrentTransactions();
} catch (Error | RuntimeException t) { // some libs throw Errors: e.g.
// javax.xml.ws.spi.FactoryFinder$ConfigurationError
isHealthy = false;
- logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
+ LOGGER.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
int orderingIdx = 0;
for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
- logger.trace("Registering {}", moduleIdentifier);
+ LOGGER.trace("Registering {}", moduleIdentifier);
ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
.get(moduleIdentifier);
if (entry == null) {
configTransactionControllerEntry.getValue().close();
configTransactionController.abortConfig();
} catch (RuntimeException e) {
- logger.warn("Ignoring exception while aborting {}",
+ LOGGER.warn("Ignoring exception while aborting {}",
configTransactionController, e);
}
}
@Override
public Set<ObjectName> lookupRuntimeBeans(String moduleName,
String instanceName) {
- if (moduleName == null) {
- moduleName = "*";
- }
- if (instanceName == null) {
- instanceName = "*";
- }
+ String finalModuleName = moduleName == null ? "*" : moduleName;
+ String finalInstanceName = instanceName == null ? "*" : instanceName;
ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
- moduleName, instanceName);
+ finalModuleName, finalInstanceName);
return baseJMXRegistrator.queryNames(namePattern, null);
}
* Service Registry.
*/
public void addAll(Collection<ModuleInternalInfo> configInfos) {
- if (currentConfig.size() > 0) {
+ if (!currentConfig.isEmpty()) {
throw new IllegalStateException(
"Error - some config entries were not removed: "
+ currentConfig);
ConfigTransactionControllerInternal,
ConfigTransactionControllerImplMXBean,
Identifiable<TransactionIdentifier> {
- private static final Logger logger = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
private final ConfigTransactionLookupRegistry txLookupRegistry;
private final ObjectName controllerON;
boolean isDefaultBean, BundleContext bundleContext)
throws InstanceAlreadyExistsException {
- logger.debug("Adding module {} to transaction {}", moduleIdentifier, this);
+ LOGGER.debug("Adding module {} to transaction {}", moduleIdentifier, this);
if (moduleIdentifier.equals(module.getIdentifier()) == false) {
throw new IllegalStateException("Incorrect name reported by module. Expected "
+ moduleIdentifier + ", got " + module.getIdentifier());
}
private synchronized void destroyModule(ModuleIdentifier moduleIdentifier) {
- logger.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
+ LOGGER.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
transactionStatus.checkNotAborted();
ModuleInternalTransactionalInfo found = dependencyResolverManager.findModuleInternalTransactionalInfo(moduleIdentifier);
- if (blankTransaction == false) {
-
- if (found.isDefaultBean()) {
- logger.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
- }
+ if (blankTransaction == false &&
+ found.isDefaultBean()) {
+ LOGGER.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
}
// first remove refNames, it checks for objectname existence
writableSRRegistry.removeServiceReferences(
ObjectNameUtil.createTransactionModuleON(getTransactionName(), moduleIdentifier));
} catch (InstanceNotFoundException e) {
- logger.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
+ LOGGER.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
throw new IllegalStateException("Possible code error: cannot find " + moduleIdentifier, e);
}
}
configBeanModificationDisabled.set(true);
try {
- validate_noLocks();
+ validateNoLocks();
} finally {
configBeanModificationDisabled.set(false);
}
}
- private void validate_noLocks() throws ValidationException {
+ private void validateNoLocks() throws ValidationException {
transactionStatus.checkNotAborted();
- logger.trace("Validating transaction {}", getTransactionIdentifier());
+ LOGGER.trace("Validating transaction {}", getTransactionIdentifier());
// call validate()
List<ValidationException> collectedExceptions = new ArrayList<>();
for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
try {
module.validate();
} catch (Exception e) {
- logger.warn("Validation exception in {}", getTransactionName(),
+ LOGGER.warn("Validation exception in {}", getTransactionName(),
e);
collectedExceptions.add(ValidationException
.createForSingleException(name, e));
}
}
- if (collectedExceptions.size() > 0) {
+ if (!collectedExceptions.isEmpty()) {
throw ValidationException
.createFromCollectedValidationExceptions(collectedExceptions);
}
- logger.trace("Validated transaction {}", getTransactionIdentifier());
+ LOGGER.trace("Validated transaction {}", getTransactionIdentifier());
}
/**
transactionStatus.checkNotCommitStarted();
configBeanModificationDisabled.set(true);
try {
- validate_noLocks();
+ validateNoLocks();
} catch (ValidationException e) {
- logger.trace("Commit failed on validation");
+ LOGGER.trace("Commit failed on validation");
configBeanModificationDisabled.set(false); // recoverable error
throw e;
}
+ "to obtain a lock");
}
- logger.trace("Committing transaction {}", getTransactionIdentifier());
+ LOGGER.trace("Committing transaction {}", getTransactionIdentifier());
// call getInstance()
for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager
Module module = entry.getValue();
ModuleIdentifier name = entry.getKey();
try {
- logger.debug("About to commit {} in transaction {}",
+ LOGGER.debug("About to commit {} in transaction {}",
name, getTransactionIdentifier());
AutoCloseable instance = module.getInstance();
checkNotNull(instance, "Instance is null:{} in transaction {}", name, getTransactionIdentifier());
} catch (Exception e) {
- logger.error("Commit failed on {} in transaction {}", name,
+ LOGGER.error("Commit failed on {} in transaction {}", name,
getTransactionIdentifier(), e);
internalAbort();
throw new IllegalStateException(
// count dependency order
- logger.trace("Committed configuration {}", getTransactionIdentifier());
+ LOGGER.trace("Committed configuration {}", getTransactionIdentifier());
transactionStatus.setCommitted();
return dependencyResolverManager.getSortedModuleIdentifiers();
}
private void internalAbort() {
- logger.trace("Aborting {}", this);
+ LOGGER.trace("Aborting {}", this);
transactionStatus.setAborted();
close();
}
import java.util.concurrent.TimeUnit;
public class DeadlockMonitor implements AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(DeadlockMonitorRunnable.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(DeadlockMonitorRunnable.class);
private static final long WARN_AFTER_MILLIS = 5000;
moduleIdentifierWithNanosStack.push(current);
top = current;
}
- logger.trace("setCurrentlyInstantiatedModule {}, top {}", currentlyInstantiatedModule, top);
+ LOGGER.trace("setCurrentlyInstantiatedModule {}, top {}", currentlyInstantiatedModule, top);
}
public boolean isAlive() {
// is the getInstance() running longer than WARN_AFTER_MILLIS ?
long runningTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - copy.nanoTime);
if (runningTime > WARN_AFTER_MILLIS) {
- logger.warn("{} did not finish after {} ms", copy.moduleIdentifier, runningTime);
+ LOGGER.warn("{} did not finish after {} ms", copy.moduleIdentifier, runningTime);
}
}
try {
interrupt();
}
}
- logger.trace("Exiting {}", this);
+ LOGGER.trace("Exiting {}", this);
}
@Override
@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;
+ }
ModuleIdentifierWithNanos that = (ModuleIdentifierWithNanos) o;
- if (nanoTime != that.nanoTime) return false;
- if (moduleIdentifier != null ? !moduleIdentifier.equals(that.moduleIdentifier) : that.moduleIdentifier != null)
+ if (nanoTime != that.nanoTime) {
return false;
+ }
+ if (moduleIdentifier != null ? !moduleIdentifier.equals(that.moduleIdentifier) : that.moduleIdentifier != null) {
+ return false;
+ }
return true;
}
import org.slf4j.LoggerFactory;
public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
- private static final Logger logger = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
private final Map<String, ModuleFactory> factories;
private final Map<String, Set<String>> factoryNamesToQNames;
boolean skipChecks = true;
newRegistry.saveServiceReference(refNameEntry.getKey(), currentImplementation, skipChecks);
} catch (InstanceNotFoundException e) {
- logger.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
+ LOGGER.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
throw new IllegalStateException("Possible code error", e);
}
}
Map<String, Set<String /* QName */>> modifiableFactoryNamesToQNames = new HashMap<>();
Set<ServiceInterfaceAnnotation> allAnnotations = new HashSet<>();
- Set<String /* qName */> allQNames = new HashSet<>();
+ Set<String /* qName */> allQNameSet = new HashSet<>();
for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
if (entry.getKey().equals(entry.getValue().getImplementationName()) == false) {
- logger.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
+ LOGGER.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);
}
Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue());
Set<String> qNames = InterfacesHelper.getQNames(siAnnotations);
allAnnotations.addAll(siAnnotations);
- allQNames.addAll(qNames);
+ allQNameSet.addAll(qNames);
modifiableFactoryNamesToQNames.put(entry.getKey(), Collections.unmodifiableSet(qNames));
}
this.factoryNamesToQNames = Collections.unmodifiableMap(modifiableFactoryNamesToQNames);
- this.allQNames = Collections.unmodifiableSet(allQNames);
+ this.allQNames = Collections.unmodifiableSet(allQNameSet);
// fill namespacesToAnnotations
Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> modifiableNamespacesToAnnotations =
new HashMap<>();
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 {}",
+ LOGGER.error("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());
}
}
this.namespacesToAnnotations = Collections.unmodifiableMap(modifiableNamespacesToAnnotations);
this.serviceQNamesToAnnotations = Collections.unmodifiableMap(modifiableServiceQNamesToAnnotations);
- logger.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
+ LOGGER.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
}
@Override
String factoryName = ObjectNameUtil.getFactoryName(objectName);
Set<String> serviceInterfaceAnnotations = factoryNamesToQNames.get(factoryName);
if (serviceInterfaceAnnotations == null) {
- logger.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
+ LOGGER.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
factoryName, objectName, factoryNamesToQNames);
throw new IllegalArgumentException("Cannot find factory with name " + factoryName);
}
public synchronized String getServiceInterfaceName(String namespace, String localName) {
Map<String /* localName */, ServiceInterfaceAnnotation> ofNamespace = namespacesToAnnotations.get(namespace);
if (ofNamespace == null) {
- logger.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
+ LOGGER.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
throw new IllegalArgumentException("Cannot find namespace " + namespace);
}
ServiceInterfaceAnnotation sia = ofNamespace.get(localName);
if (sia == null) {
- logger.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
+ LOGGER.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
throw new IllegalArgumentException("Cannot find local name " + localName + " in namespace " + namespace);
}
return sia.value();
try {
on = lookupRegistry.lookupConfigBean(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName());
} catch (InstanceNotFoundException e) {
- logger.error("Cannot find instance {}", moduleIdentifier);
+ LOGGER.error("Cannot find instance {}", moduleIdentifier);
throw new IllegalStateException("Cannot find instance " + moduleIdentifier, e);
}
return on;
ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
ModuleIdentifier moduleIdentifier = refNames.get(serviceReference);
if (moduleIdentifier == null) {
- logger.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
+ LOGGER.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
throw new IllegalArgumentException("Cannot find " + serviceReference);
}
return getObjectName(moduleIdentifier);
Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
if (innerMap == null) {
- logger.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
+ LOGGER.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
throw new IllegalArgumentException("Cannot find " + serviceInterfaceQName);
}
return innerMap;
String referenceName = ObjectNameUtil.getReferenceName(objectName);
ServiceReference serviceReference = new ServiceReference(serviceQName, referenceName);
if (refNames.containsKey(serviceReference) == false) {
- logger.warn("Cannot find {} in {}", serviceReference, refNames);
+ LOGGER.warn("Cannot find {} in {}", serviceReference, refNames);
throw new InstanceNotFoundException("Service reference not found:" + objectName);
}
}
// check that service interface name exist
Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(moduleIdentifier.getFactoryName());
if (serviceInterfaceQNames == null) {
- logger.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
+ LOGGER.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());
}
// supplied serviceInterfaceName must exist in this collection
if (serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName()) == false) {
- logger.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
+ LOGGER.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());
}
}
private synchronized void removeServiceReference(ServiceReference serviceReference) throws InstanceNotFoundException {
- logger.debug("Removing service reference {} from {}", serviceReference, this);
+ LOGGER.debug("Removing service reference {} from {}", serviceReference, this);
assertWritable();
// is the qName known?
if (allQNames.contains(serviceReference.getServiceInterfaceQName()) == false) {
- logger.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
+ LOGGER.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName());
}
ModuleIdentifier removed = refNames.remove(serviceReference);
private Set<ServiceReference> findServiceReferencesLinkingTo(ObjectName moduleObjectName, Set<String> serviceInterfaceQNames) {
String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
if (serviceInterfaceQNames == null) {
- logger.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
+ LOGGER.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);
*/
final class DependencyResolverImpl implements DependencyResolver,
Comparable<DependencyResolverImpl> {
- private static final Logger logger = LoggerFactory.getLogger(DependencyResolverImpl.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(DependencyResolverImpl.class);
private final ModulesHolder modulesHolder;
private final ModuleIdentifier name;
), jmxAttribute
);
- dependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
+ ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
- ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(dependentReadOnlyON, ObjectNameUtil
+ ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON, ObjectNameUtil
.TYPE_MODULE);
ModuleFactory foundFactory = modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
+ "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
+ "attribute %s",
foundFactory.getImplementationName(), foundFactory,
- expectedServiceInterface, dependentReadOnlyON,
+ expectedServiceInterface, newDependentReadOnlyON,
jmxAttribute
);
throw new JmxAttributeValidationException(message, jmxAttribute);
// translate from serviceref to module ON
private ObjectName translateServiceRefIfPossible(ObjectName dependentReadOnlyON) {
- if (ObjectNameUtil.isServiceReference(dependentReadOnlyON)) {
- String serviceQName = ObjectNameUtil.getServiceQName(dependentReadOnlyON);
- String refName = ObjectNameUtil.getReferenceName(dependentReadOnlyON);
- dependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
+ ObjectName translatedDependentReadOnlyON = dependentReadOnlyON;
+ if (ObjectNameUtil.isServiceReference(translatedDependentReadOnlyON)) {
+ String serviceQName = ObjectNameUtil.getServiceQName(translatedDependentReadOnlyON);
+ String refName = ObjectNameUtil.getReferenceName(translatedDependentReadOnlyON);
+ translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
}
- return dependentReadOnlyON;
+ return translatedDependentReadOnlyON;
}
/**
"Null parameters not allowed, got %s %s %s", expectedType,
dependentReadOnlyON, jmxAttribute));
}
- dependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
+ ObjectName translatedDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
transactionStatus.checkCommitStarted();
transactionStatus.checkNotCommitted();
ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(
- dependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
+ translatedDependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
Module module = modulesHolder.findModule(dependentModuleIdentifier,
jmxAttribute);
synchronized (this) {
if (expectedBaseClass.isAssignableFrom(deserialized)) {
return (Class<T>) deserialized;
} else {
- logger.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.",
+ LOGGER.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);
}
@Override
public Object getAttribute(ObjectName name, String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
- name = translateServiceRefIfPossible(name);
+ ObjectName newName = translateServiceRefIfPossible(name);
// add transaction name
- name = ObjectNameUtil.withTransactionName(name, transactionName);
- return mBeanServer.getAttribute(name, attribute);
+ newName = ObjectNameUtil.withTransactionName(newName, transactionName);
+ return mBeanServer.getAttribute(newName, attribute);
}
@Override
public <T> T newMXBeanProxy(ObjectName name, Class<T> interfaceClass) {
- name = translateServiceRefIfPossible(name);
+ ObjectName newName = translateServiceRefIfPossible(name);
// add transaction name
- name = ObjectNameUtil.withTransactionName(name, transactionName);
- return JMX.newMXBeanProxy(mBeanServer, name, interfaceClass);
+ newName = ObjectNameUtil.withTransactionName(newName, transactionName);
+ return JMX.newMXBeanProxy(mBeanServer, newName, interfaceClass);
}
}
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
- boolean isGetInstance = method.getName().equals("getInstance");
+ boolean isGetInstance = "getInstance".equals(method.getName());
if (isGetInstance) {
if (cachedInstance != null) {
return cachedInstance;
*/
public class DestroyedModule implements AutoCloseable,
Comparable<DestroyedModule>, Identifiable<ModuleIdentifier> {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(DestroyedModule.class);
private final ModuleIdentifier identifier;
@Override
public void close() {
- logger.trace("Destroying {}", identifier);
+ LOGGER.trace("Destroying {}", identifier);
try {
instance.close();
} catch (Exception e) {
- logger.error("Error while closing instance of {}", identifier, e);
+ LOGGER.error("Error while closing instance of {}", identifier, e);
}
try {
oldJMXRegistrator.close();
} catch (Exception e) {
- logger.error("Error while closing jmx registrator of {}", identifier, e);
+ LOGGER.error("Error while closing jmx registrator of {}", identifier, e);
}
try {
osgiRegistration.close();
} catch (Exception e) {
- logger.error("Error while closing osgi registration of {}", identifier, e);
+ LOGGER.error("Error while closing osgi registration of {}", identifier, e);
}
}
* a read only wrapper.
*/
abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(AbstractDynamicWrapper.class);
protected final boolean writable;
public Object getAttribute(String attributeName)
throws AttributeNotFoundException, MBeanException,
ReflectionException {
- if (attributeName.equals("MBeanInfo")) {
+ if ("MBeanInfo".equals(attributeName)) {
return getMBeanInfo();
}
result.add(new Attribute(attributeName, value));
} catch (Exception e) {
- logger.debug("Getting attribute {} failed", attributeName, e);
+ LOGGER.debug("Getting attribute {} failed", attributeName, e);
}
}
return result;
&& signature[0].equals(AttributeList.class.getName())) {
return setAttributes((AttributeList) params[0]);
} else {
- logger.debug("Operation not found {} ", actionName);
+ LOGGER.debug("Operation not found {} ", actionName);
throw new UnsupportedOperationException(
format("Operation not found on %s. Method invoke is only supported for getInstance and getAttribute(s) "
+ "method, got actionName %s, params %s, signature %s ",
public 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.
for (RequireInterface ri : foundRequireInterfaces) {
foundValues.add(ri.value());
}
- if (foundValues.size() == 0) {
+ if (foundValues.isEmpty()) {
return null;
} else if (foundValues.size() > 1) {
throw new IllegalStateException("Error finding @RequireInterface. "
public Object getAttribute(String attributeName)
throws AttributeNotFoundException, MBeanException,
ReflectionException {
- if (attributeName.equals("getInstance")) {
+ if ("getInstance".equals(attributeName)) {
return getInstance();
}
return super.getAttribute(attributeName);
*/
@ThreadSafe
public class DynamicWritableWrapper extends AbstractDynamicWrapper {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(DynamicWritableWrapper.class);
private final ReadOnlyAtomicBoolean configBeanModificationDisabled;
@Override
public synchronized void setAttribute(Attribute attribute)
throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
+ Attribute newAttribute = attribute;
if (configBeanModificationDisabled.get() == true) {
throw new IllegalStateException("Operation is not allowed now");
}
- if (attribute.getName().equals("Attribute")) {
- setAttribute((Attribute) attribute.getValue());
+ if ("Attribute".equals(newAttribute.getName())) {
+ setAttribute((Attribute) newAttribute.getValue());
return;
}
try {
- if (attribute.getValue() instanceof ObjectName) {
- attribute = fixDependencyAttribute(attribute);
- } else if (attribute.getValue() instanceof ObjectName[]) {
- attribute = fixDependencyListAttribute(attribute);
+ if (newAttribute.getValue() instanceof ObjectName) {
+ newAttribute = fixDependencyAttribute(newAttribute);
+ } else if (newAttribute.getValue() instanceof ObjectName[]) {
+ newAttribute = fixDependencyListAttribute(newAttribute);
}
- internalServer.setAttribute(objectNameInternal, attribute);
+ internalServer.setAttribute(objectNameInternal, newAttribute);
} catch (InstanceNotFoundException e) {
throw new MBeanException(e);
}
}
private Attribute fixDependencyListAttribute(Attribute attribute) {
- AttributeHolder attributeHolder = attributeHolderMap.get(attribute.getName());
+ Attribute newAttribute = attribute;
+ AttributeHolder attributeHolder = attributeHolderMap.get(newAttribute.getName());
if (attributeHolder.getRequireInterfaceOrNull() != null) {
- attribute = new Attribute(attribute.getName(), fixObjectNames((ObjectName[]) attribute.getValue()));
+ newAttribute = new Attribute(newAttribute.getName(), fixObjectNames((ObjectName[]) newAttribute.getValue()));
}
- return attribute;
+ return newAttribute;
}
private Attribute fixDependencyAttribute(Attribute attribute) {
- AttributeHolder attributeHolder = attributeHolderMap.get(attribute.getName());
+ Attribute newAttribute = attribute;
+ AttributeHolder attributeHolder = attributeHolderMap.get(newAttribute.getName());
if (attributeHolder.getRequireInterfaceOrNull() != null) {
- attribute = new Attribute(attribute.getName(), fixObjectName((ObjectName) attribute.getValue()));
+ newAttribute = new Attribute(newAttribute.getName(), fixObjectName((ObjectName) newAttribute.getValue()));
} else {
- attribute = new Attribute(attribute.getName(), attribute.getValue());
+ newAttribute = new Attribute(newAttribute.getName(), newAttribute.getValue());
}
- return attribute;
+ return newAttribute;
}
private ObjectName[] fixObjectNames(ObjectName[] dependencies) {
setAttribute(attribute);
result.add(attribute);
} catch (Exception e) {
- logger.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
+ LOGGER.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
throw new IllegalArgumentException(
"Setting attribute failed - " + attribute.getName()
+ " on " + moduleIdentifier, e);
import java.util.Set;
public class InternalJMXRegistrator implements Closeable {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(InternalJMXRegistrator.class);
private final MBeanServer configMBeanServer;
try {
configMBeanServer.unregisterMBean(on);
} catch (Exception e) {
- logger.warn("Ignoring error while unregistering {}", on, e);
+ LOGGER.warn("Ignoring error while unregistering {}", on, e);
}
}
registeredObjectNames.clear();
public ModuleJMXRegistration registerMBean(Object object, ObjectName on)
throws InstanceAlreadyExistsException {
ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_MODULE);
- if (ObjectNameUtil.getTransactionName(on) != null)
+ if (ObjectNameUtil.getTransactionName(on) != null) {
throw new IllegalArgumentException(
"Transaction name not expected in " + on);
+ }
return new ModuleJMXRegistration(childJMXRegistrator.registerMBean(
object, on));
}
public static class OsgiRegistration implements AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(OsgiRegistration.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(OsgiRegistration.class);
@GuardedBy("this")
private AutoCloseable instance;
try {
serviceRegistration.unregister();
} catch(IllegalStateException e) {
- logger.trace("Cannot unregister {}", serviceRegistration, e);
+ LOGGER.trace("Cannot unregister {}", serviceRegistration, e);
}
}
serviceRegistrations.clear();
notEquals |= newAnnotationMapping.equals(serviceNamesToAnnotations) == false;
if (notEquals) {
// FIXME: changing from old state to new state can be improved by computing the diff
- logger.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
+ LOGGER.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
serviceNamesToAnnotations, newAnnotationMapping);
close();
this.instance = newInstance;
* functionality.
*/
public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<ModuleFactory, Object> {
- private static final Logger logger = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
public static final int DEFAULT_MAX_ATTEMPTS = 10;
try {
// create transaction
CommitStatus commitStatus = blankTransaction.hit();
- logger.debug("Committed blank transaction with status {}", commitStatus);
+ LOGGER.debug("Committed blank transaction with status {}", commitStatus);
return;
} catch (ConflictingVersionException e) {
lastException = e;
throw new IllegalStateException(interruptedException);
}
} catch (ValidationException e) {
- logger.error("Validation exception while running blank transaction indicates programming error", e);
+ LOGGER.error("Validation exception while running blank transaction indicates programming error", e);
throw new RuntimeException("Validation exception while running blank transaction indicates programming error", e);
}
}
*/
public class BundleContextBackedModuleFactoriesResolver implements
ModuleFactoriesResolver {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(BundleContextBackedModuleFactoriesResolver.class);
private final BundleContext bundleContext;
if (serviceReference.getBundle() == null || serviceReference.getBundle().getBundleContext() == null) {
throw new NullPointerException("Bundle context of " + factory + " ModuleFactory not found.");
}
- logger.debug("Reading factory {} {}", moduleName, factory);
+ LOGGER.debug("Reading factory {} {}", moduleName, factory);
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);
- logger.error(error);
+ LOGGER.error(error);
throw new IllegalArgumentException(error);
} else {
result.put(moduleName, new AbstractMap.SimpleImmutableEntry<>(factory,
*/
public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Object> {
private final BlankTransactionServiceTracker blankTransactionServiceTracker;
- private static final Logger logger = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
public ModuleFactoryBundleTracker(BlankTransactionServiceTracker blankTransactionServiceTracker) {
this.blankTransactionServiceTracker = blankTransactionServiceTracker;
@Override
public Object addingBundle(Bundle bundle, BundleEvent event) {
URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
- logger.trace("Got addingBundle event of bundle {}, resource {}, event {}",
+ LOGGER.trace("Got addingBundle event of bundle {}, resource {}, event {}",
bundle, resource, event);
if (resource != null) {
try (InputStream inputStream = resource.openStream()) {
registerFactory(factoryClassName, bundle);
}
} catch (Exception e) {
- logger.error("Error while reading {}", resource, e);
+ LOGGER.error("Error while reading {}", resource, e);
throw new RuntimeException(e);
}
}
Class<?> clazz = bundle.loadClass(factoryClassName);
if (ModuleFactory.class.isAssignableFrom(clazz)) {
try {
- logger.debug("Registering {} in bundle {}",
+ LOGGER.debug("Registering {} in bundle {}",
clazz.getName(), bundle);
return bundle.getBundleContext().registerService(
ModuleFactory.class.getName(), clazz.newInstance(),
}
public static String logMessage(String slfMessage, Object... params) {
- logger.info(slfMessage, params);
+ LOGGER.info(slfMessage, params);
String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
return format(formatMessage, params);
}
*/
public final class ModuleInfoBundleTracker implements BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
- private static final Logger logger = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
public static final String MODULE_INFO_PROVIDER_PATH_PREFIX = "META-INF/services/";
@Override
public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(Bundle bundle, BundleEvent event) {
URL resource = bundle.getEntry(MODULE_INFO_PROVIDER_PATH_PREFIX + YangModelBindingProvider.class.getName());
- logger.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
+ LOGGER.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
if(resource==null) {
return null;
}
try (InputStream inputStream = resource.openStream()) {
List<String> lines = IOUtils.readLines(inputStream);
for (String moduleInfoName : lines) {
- logger.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
+ LOGGER.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
YangModuleInfo moduleInfo = retrieveModuleInfo(moduleInfoName, bundle);
registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
}
} catch (Exception e) {
- logger.error("Error while reading {}", resource, e);
+ LOGGER.error("Error while reading {}", resource, e);
throw new RuntimeException(e);
}
- logger.trace("Got following registrations {}", registrations);
+ LOGGER.trace("Got following registrations {}", registrations);
return registrations;
}
} catch (NoClassDefFoundError e) {
- logger.error("Error while executing getModuleInfo on {}", instance, e);
+ LOGGER.error("Error while executing getModuleInfo on {}", instance, e);
throw e;
}
}
}
public static String logMessage(String slfMessage, Object... params) {
- logger.info(slfMessage, params);
+ LOGGER.info(slfMessage, params);
String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
return format(formatMessage, params);
}
public class InterfacesHelper {
+ private InterfacesHelper() {
+ }
+
public static Set<Class<?>> getAllInterfaces(Class<?> clazz) {
if (clazz.isInterface()) {
throw new IllegalArgumentException(clazz
}
private static Set<Class<?>> getAllSuperInterfaces(Set<Class<?>> ifcs) {
- ifcs = new HashSet<>(ifcs); // create copy to modify
+ Set<Class<?>> interfaces = new HashSet<>(ifcs); // create copy to modify
// each interface can extend other interfaces
Set<Class<?>> result = new HashSet<>();
- while (ifcs.size() > 0) {
- Iterator<Class<?>> iterator = ifcs.iterator();
+ while (!interfaces.isEmpty()) {
+ Iterator<Class<?>> iterator = interfaces.iterator();
Class<?> ifc = iterator.next();
iterator.remove();
if (ifc.isInterface() == false) {
throw new IllegalArgumentException(ifc + " should be an interface");
}
- ifcs.addAll(Arrays.asList(ifc.getInterfaces()));
+ interfaces.addAll(Arrays.asList(ifc.getInterfaces()));
result.add(ifc);
}
return result;
public class LookupBeansUtil {
+ private LookupBeansUtil() {
+ }
+
public static ObjectName lookupConfigBean(LookupRegistry lookupRegistry,
String moduleName, String instanceName)
throws InstanceNotFoundException {
Set<ObjectName> objectNames = lookupRegistry.lookupConfigBeans(
moduleName, instanceName);
- if (objectNames.size() == 0) {
+ if (objectNames.isEmpty()) {
throw new InstanceNotFoundException("No instance found");
} else if (objectNames.size() > 1) {
throw new InstanceNotFoundException("Too many instances found");
public class ModuleQNameUtil {
+ private ModuleQNameUtil() {
+ }
+
public static Set<String> getQNames(Map<String, Entry<ModuleFactory, BundleContext>> resolved) {
Set<String> result = new HashSet<>();
for (Entry<ModuleFactory, BundleContext> entry : resolved.values()) {
import org.slf4j.LoggerFactory;
public class OsgiRegistrationUtil {
- private static final Logger logger = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
+
+ private OsgiRegistrationUtil() {
+ }
@SafeVarargs
public static <T> AutoCloseable registerService(BundleContext bundleContext, T service, Class<? super T> ... interfaces) {
try {
ac.close();
} catch (Exception e) {
- logger.warn("Exception while closing {}", ac, e);
+ LOGGER.warn("Exception while closing {}", ac, e);
if (firstException == null) {
firstException = e;
} else {
* Delegates the the contained feature and provides additional methods.
*/
public class AbstractFeatureWrapper implements Feature {
- private static final Logger logger = LoggerFactory.getLogger(AbstractFeatureWrapper.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFeatureWrapper.class);
protected Feature feature = null;
protected AbstractFeatureWrapper() {
try {
snapShotHolders.add(new FeatureConfigSnapshotHolder(c,this));
} catch (JAXBException e) {
- logger.debug("{} is not a config subsystem config file",c.getFinalname());
+ LOGGER.debug("{} is not a config subsystem config file",c.getFinalname());
}
}
return snapShotHolders;
@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;
+ }
AbstractFeatureWrapper other = (AbstractFeatureWrapper) obj;
if (feature == null) {
- if (other.feature != null)
+ if (other.feature != null) {
return false;
- } else if (!feature.equals(other.feature))
+ }
+ } else if (!feature.equals(other.feature)) {
return false;
+ }
return true;
}
* Delegates the the contained feature and provides additional methods.
*/
public class ChildAwareFeatureWrapper extends AbstractFeatureWrapper implements Feature {
- private static final Logger logger = LoggerFactory.getLogger(ChildAwareFeatureWrapper.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ChildAwareFeatureWrapper.class);
private FeaturesService featuresService= null;
protected ChildAwareFeatureWrapper(Feature f) {
f = new FeatureConfigSnapshotHolder(h,this);
snapShotHolders.add(f);
} catch (JAXBException e) {
- logger.debug("{} is not a config subsystem config file",h.getFileInfo().getFinalname());
+ LOGGER.debug("{} is not a config subsystem config file",h.getFileInfo().getFinalname());
}
}
}
for(Feature f: features) {
if (f.getName().equals(dependency.getName())) {
Version v = VersionTable.getVersion(f.getVersion());
- if (range.contains(v)) {
- if (fi == null || VersionTable.getVersion(fi.getVersion()).compareTo(v) < 0) {
+ if (range.contains(v) &&
+ (fi == null || VersionTable.getVersion(fi.getVersion()).compareTo(v) < 0)) {
fi = f;
break;
- }
}
}
}
import org.slf4j.LoggerFactory;
public class ConfigFeaturesListener implements FeaturesListener, AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(ConfigFeaturesListener.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFeaturesListener.class);
private static final int QUEUE_SIZE = 1000;
private BlockingQueue<FeatureEvent> queue = new LinkedBlockingQueue<FeatureEvent>(QUEUE_SIZE);
Thread pushingThread = null;
@Override
public void repositoryEvent(RepositoryEvent event) {
- logger.debug("Repository: " + event.getType() + " " + event.getRepository());
+ LOGGER.debug("Repository: " + event.getType() + " " + event.getRepository());
}
@Override
import org.slf4j.LoggerFactory;
public class ConfigPusherCustomizer implements ServiceTrackerCustomizer<ConfigPusher, ConfigPusher>, AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(ConfigPusherCustomizer.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPusherCustomizer.class);
private ConfigFeaturesListener configFeaturesListener = null;
private FeatureServiceCustomizer featureServiceCustomizer = null;
private ServiceTracker<FeaturesService,FeaturesService> fsst = null;
@Override
public ConfigPusher addingService(ServiceReference<ConfigPusher> configPusherServiceReference) {
- logger.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference);
+ LOGGER.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference);
BundleContext bc = configPusherServiceReference.getBundle().getBundleContext();
ConfigPusher cpService = bc.getService(configPusherServiceReference);
featureServiceCustomizer = new FeatureServiceCustomizer(cpService);
import com.google.common.collect.LinkedHashMultimap;
public class ConfigPushingRunnable implements Runnable {
- private static final Logger logger = LoggerFactory.getLogger(ConfigPushingRunnable.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPushingRunnable.class);
private static final int POLL_TIME = 1;
private BlockingQueue<FeatureEvent> queue;
private FeatureConfigPusher configPusher;
processFeatureEvent(event,toInstall);
}
} else if(toInstall.isEmpty()) {
- logger.error("ConfigPushingRunnable - exiting");
+ LOGGER.error("ConfigPushingRunnable - exiting");
return;
}
} catch (InterruptedException e) {
- logger.error("ConfigPushingRunnable - interupted");
+ LOGGER.error("ConfigPushingRunnable - interupted");
interuppted = true;
} catch (Exception e) {
- logger.error("Exception while processing features {}", e);
+ LOGGER.error("Exception while processing features {}", e);
}
}
}
protected void logPushResult(LinkedHashMultimap<Feature,FeatureConfigSnapshotHolder> results) {
for(Feature f:results.keySet()) {
- logger.info("Pushed configs for feature {} {}",f,results.get(f));
+ LOGGER.info("Pushed configs for feature {} {}",f,results.get(f));
}
}
}
* Simple class to push configs to the config subsystem from Feature's configfiles
*/
public class FeatureConfigPusher {
- private static final Logger logger = LoggerFactory.getLogger(FeatureConfigPusher.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(FeatureConfigPusher.class);
private static final int MAX_RETRIES=100;
private static final int RETRY_PAUSE_MILLIS=1;
private FeaturesService featuresService = null;
if(installedFeatures.contains(feature)) {
return true;
} else {
- logger.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion());
+ LOGGER.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion());
}
} catch (Exception e) {
if(retries < MAX_RETRIES) {
- logger.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}, Exception {}", retries,e);
+ LOGGER.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}, Exception {}", retries,e);
} else {
- logger.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}, Exception {}", retries,e);
+ LOGGER.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}, Exception {}", retries,e);
throw e;
}
}
throw new IllegalStateException(e1);
}
}
- logger.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion());
+ LOGGER.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion());
return false;
}
* StorageAdapter that stores configuration in an xml file.
*/
public class XmlFileStorageAdapter implements StorageAdapter, Persister {
- private static final Logger logger = LoggerFactory.getLogger(XmlFileStorageAdapter.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(XmlFileStorageAdapter.class);
public static final String FILE_STORAGE_PROP = "fileStorage";
public static final String NUMBER_OF_BACKUPS = "numberOfBackups";
@Override
public Persister instantiate(PropertiesProvider propertiesProvider) {
File storage = extractStorageFileFromProperties(propertiesProvider);
- logger.debug("Using file {}", storage.getAbsolutePath());
+ LOGGER.debug("Using file {}", storage.getAbsolutePath());
// Create file if it does not exist
File parentFile = storage.getAbsoluteFile().getParentFile();
if (parentFile.exists() == false) {
- logger.debug("Creating parent folders {}", parentFile);
+ LOGGER.debug("Creating parent folders {}", parentFile);
parentFile.mkdirs();
}
if (storage.exists() == false) {
- logger.debug("Storage file does not exist, creating empty file");
+ LOGGER.debug("Storage file does not exist, creating empty file");
try {
boolean result = storage.createNewFile();
if (result == false)
} else {
numberOfStoredBackups = Integer.MAX_VALUE;
}
- logger.trace("Property {} set to {}", NUMBER_OF_BACKUPS, numberOfStoredBackups);
+ LOGGER.trace("Property {} set to {}", NUMBER_OF_BACKUPS, numberOfStoredBackups);
return result;
}
Optional<ConfigSnapshot> lastSnapshot = Config.fromXml(storage).getLastSnapshot();
- if (lastSnapshot.isPresent())
+ if (lastSnapshot.isPresent()) {
return Lists.newArrayList(toConfigSnapshot(lastSnapshot.get()));
- else
+ } else {
return Collections.emptyList();
+ }
}
@Override
public String toString() {
- final StringBuffer sb = new StringBuffer("ConfigSnapshot{");
+ final StringBuilder sb = new StringBuilder("ConfigSnapshot{");
sb.append("configSnapshot='").append(configSnapshot).append('\'');
sb.append(", capabilities=").append(capabilities);
sb.append('}');
final class StringTrimAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) throws Exception {
- if (v == null)
+ if (v == null) {
return null;
+ }
return v.trim();
}
@Override
public String marshal(String v) throws Exception {
- if (v == null)
+ if (v == null) {
return null;
+ }
return v.trim();
}
}
*/
@Deprecated
public <T> T newMBeanProxy(ObjectName on, Class<T> clazz) {
- on = translateServiceRefIfPossible(on, clazz, configMBeanServer);
- return JMX.newMBeanProxy(configMBeanServer, on, clazz);
+ ObjectName onObj = translateServiceRefIfPossible(on, clazz, configMBeanServer);
+ return JMX.newMBeanProxy(configMBeanServer, onObj, clazz);
}
static ObjectName translateServiceRefIfPossible(ObjectName on, Class<?> clazz, MBeanServer configMBeanServer) {
- if (ObjectNameUtil.isServiceReference(on) && clazz.equals(ServiceReferenceMXBean.class) == false) {
- ServiceReferenceMXBean proxy = JMX.newMXBeanProxy(configMBeanServer, on, ServiceReferenceMXBean.class);
- on = proxy.getCurrentImplementation();
+ ObjectName onObj = on;
+ if (ObjectNameUtil.isServiceReference(onObj) && clazz.equals(ServiceReferenceMXBean.class) == false) {
+ ServiceReferenceMXBean proxy = JMX.newMXBeanProxy(configMBeanServer, onObj, ServiceReferenceMXBean.class);
+ onObj = proxy.getCurrentImplementation();
}
- return on;
+ return onObj;
}
}
public <T> T newMXBeanProxy(ObjectName on, Class<T> clazz) {
+ ObjectName onName = on;
// if on is without transaction, add it. Reason is that when using getters on MXBeans the transaction name is stripped
- on = ObjectNameUtil.withTransactionName(on, getTransactionName());
+ onName = ObjectNameUtil.withTransactionName(onName, getTransactionName());
// if this is service reference and user requests for implementation, look it up
- on = ConfigRegistryJMXClient.translateServiceRefIfPossible(on, clazz, configMBeanServer);
- on = ObjectNameUtil.withTransactionName(on, getTransactionName());
- return JMX.newMXBeanProxy(configMBeanServer, on, clazz);
+ onName = ConfigRegistryJMXClient.translateServiceRefIfPossible(onName, clazz, configMBeanServer);
+ onName = ObjectNameUtil.withTransactionName(onName, getTransactionName());
+ return JMX.newMXBeanProxy(configMBeanServer, onName, clazz);
}
/**
@Override
public void setAttribute(ObjectName on, String attrName, Attribute attribute) {
- if (ObjectNameUtil.getTransactionName(on) == null)
+ if (ObjectNameUtil.getTransactionName(on) == null) {
throw new IllegalArgumentException("Not in transaction instance "
+ on + ", no transaction name present");
+ }
try {
configMBeanServer.setAttribute(on, attribute);
@Override
public Attribute getAttribute(ObjectName on, String attrName) {
- if (ObjectNameUtil.getTransactionName(on) == null)
+ if (ObjectNameUtil.getTransactionName(on) == null) {
throw new IllegalArgumentException("Not in transaction instance "
+ on + ", no transaction name present");
+ }
try {
return new Attribute(attrName, configMBeanServer.getAttribute(on,attrName));
public class ContextSetterImpl implements ContextSetter, Closeable {
private final LogbackStatusListener statusListener;
- private static final org.slf4j.Logger classLogger = LoggerFactory.getLogger(ContextSetterImpl.class);
+ private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ContextSetterImpl.class);
public ContextSetterImpl(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
statusListener = new LogbackStatusListener(rootRuntimeBeanRegistratorWrapper);
Map<String, Appender<ILoggingEvent>> appendersMap = getAppenders(module, context);
for (LoggerTO logger : module.getLoggerTO()) {
- classLogger.trace("Setting configuration for logger {}", logger.getLoggerName());
+ LOGGER.trace("Setting configuration for logger {}", logger.getLoggerName());
final ch.qos.logback.classic.Logger logbackLogger = context.getLogger(logger.getLoggerName());
Optional<Set<Appender<ILoggingEvent>>> appendersBefore = getAppendersBefore(loggersBefore, logbackLogger);
- classLogger.trace("Logger {}: Appenders registered before: {}", logger.getLoggerName(),
+ LOGGER.trace("Logger {}: Appenders registered before: {}", logger.getLoggerName(),
appendersBefore.isPresent() ? appendersBefore.get() : "NO APPENDERS BEFORE");
logbackLogger.setLevel(Level.toLevel(logger.getLevel()));
for (String appenderName : logger.getAppenders()) {
if (appendersMap.containsKey(appenderName)) {
logbackLogger.addAppender(appendersMap.get(appenderName));
- classLogger.trace("Logger {}: Adding new appender: {}", logger.getLoggerName(), appenderName);
+ LOGGER.trace("Logger {}: Adding new appender: {}", logger.getLoggerName(), appenderName);
} else {
throw new IllegalStateException("No appender " + appenderName
+ " found. This error should have been discovered by validation");
for (Appender<ILoggingEvent> appenderBefore : appendersBefore.get()) {
logbackLogger.detachAppender(appenderBefore);
appenderBefore.stop();
- classLogger.trace("Logger {}: Removing old appender: {}", logger.getLoggerName(),
+ LOGGER.trace("Logger {}: Removing old appender: {}", logger.getLoggerName(),
appenderBefore.getName());
}
loggersBefore.remove(logbackLogger);
appendersBefore.add(appenderIt.next());
}
return Optional.of(appendersBefore);
- } else
+ } else {
return Optional.absent();
+ }
}
context.getLogger(Logger.ROOT_LOGGER_NAME));
for (org.slf4j.Logger log : loggersToBeAdd) {
LoggerTO logger = new LoggerTO();
- if (((Logger) log).getLevel() != null)
+ if (((Logger) log).getLevel() != null) {
logger.setLevel(((Logger) log).getLevel().levelStr);
- else
+ } else {
logger.setLevel(((Logger) log).getEffectiveLevel().levelStr);
+ }
logger.setLoggerName(log.getName());
Iterator<Appender<ILoggingEvent>> iter = ((Logger) log).iteratorForAppenders();
while (iter.hasNext()) {
final class CodeWriter {
- private static final Logger logger = LoggerFactory.getLogger(CodeWriter.class);
- private static final Optional<String> copyright = StringUtil.loadCopyright();
+ private static final Logger LOGGER = LoggerFactory.getLogger(CodeWriter.class);
+ private static final Optional<String> COPYRIGHT = StringUtil.loadCopyright();
public File writeSie(ServiceInterfaceEntry sie, File outputBaseDir) {
try {
GeneralInterfaceTemplate generalInterfaceTemplate = TemplateFactory.serviceInterfaceFromSie(sie);
- GeneratedObject go = new GenericGeneratedObjectFactory().toGeneratedObject(generalInterfaceTemplate, copyright);
+ GeneratedObject go = new GenericGeneratedObjectFactory().toGeneratedObject(generalInterfaceTemplate, COPYRIGHT);
return go.persist(outputBaseDir).get().getValue();
} catch (Exception e) {
String message = "An error occurred during Service interface generating, sie:"
+ sie.getTypeName() + ", " + sie.getFullyQualifiedName();
- logger.error(message, e);
+ LOGGER.error(message, e);
throw new RuntimeException(message, e);
}
}
// TOs
Map<String,GeneralClassTemplate> tosFromMbe = TemplateFactory.tOsFromMbe(mbe);
for(GeneralClassTemplate template: tosFromMbe.values()) {
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, copyright), true);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, COPYRIGHT), true);
}
// MXBean interface
GeneralInterfaceTemplate ifcTemplate = TemplateFactory.mXBeanInterfaceTemplateFromMbe(mbe);
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(ifcTemplate, copyright), true);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(ifcTemplate, COPYRIGHT), true);
// generate abstract factory
- gos.put(new AbsFactoryGeneratedObjectFactory().toGeneratedObject(mbe, copyright), true);
+ gos.put(new AbsFactoryGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT), true);
// generate abstract module
- gos.put(new AbsModuleGeneratedObjectFactory().toGeneratedObject(mbe, copyright), true);
+ gos.put(new AbsModuleGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT), true);
// generate concrete factory
StubFactoryTemplate concreteFactory = TemplateFactory.stubFactoryTemplateFromMbe(mbe);
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(concreteFactory, copyright), false);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(concreteFactory, COPYRIGHT), false);
// generate concrete module
- gos.put(new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(mbe, copyright, Optional.<String>absent()), false);
+ gos.put(new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT, Optional.<String>absent()), false);
// write runtime bean MXBeans and registrators
List<FtlTemplate> allFtlFiles = getRuntimeBeanFtlTemplates(mbe.getRuntimeBeans());
for(FtlTemplate template: allFtlFiles) {
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, copyright), true);
+ gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, COPYRIGHT), true);
}
generatedFiles.addAll(persistGeneratedObjects(targetBaseDir, mainBaseDir, gos));
} catch (Exception e) {
String message = "An error occurred during Module generating, mbe:"
+ mbe.getJavaNamePrefix();
- logger.error(message, e);
+ LOGGER.error(message, e);
throw new RuntimeException(message, e);
}
}
private PackageTranslator packageTranslator;
private final CodeWriter codeWriter;
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(JMXGenerator.class);
private Map<String, String> namespaceToPackageMapping;
private File resourceBaseDir;
packageTranslator = new PackageTranslator(namespaceToPackageMapping);
- if (!outputBaseDir.exists())
+ if (!outputBaseDir.exists()) {
outputBaseDir.mkdirs();
+ }
GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
// create SIE structure qNamesToSIEs
Preconditions.checkNotNull(resourceBaseDir,
"resource base dir attribute was null");
- StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer();
+ StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
// create MBEs
for (Module module : yangModulesInCurrentMavenModule) {
String packageName = packageTranslator.getPackageName(module);
fullyQualifiedNamesOfFactories.toString());
} catch (IOException e) {
String message = "Cannot write to " + serviceLoaderFile;
- logger.error(message);
+ LOGGER.error(message);
throw new RuntimeException(message, e);
}
}
@Override
public void setAdditionalConfig(Map<String, String> additionalCfg) {
- if (logger != null)
- logger.debug(getClass().getCanonicalName(),
+ if (LOGGER != null) {
+ LOGGER.debug(getClass().getCanonicalName(),
": Additional configuration received: ",
additionalCfg.toString());
+ }
this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
}
private boolean extractModuleFactoryBoolean(
Map<String, String> additionalCfg) {
String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
- if (bool == null)
+ if (bool == null) {
return true;
- if (bool.equals("false"))
+ }
+ if ("false".equals(bool)) {
return false;
+ }
return true;
}
public void setMavenProject(MavenProject project) {
this.projectBaseDir = project.getBasedir();
- if (logger != null)
- logger.debug(getClass().getCanonicalName(), " project base dir: ",
+ if (LOGGER != null)
+ LOGGER.debug(getClass().getCanonicalName(), " project base dir: ",
projectBaseDir);
}
}
}
if (undeletedFiles.isEmpty() == false) {
- logger.error(
+ LOGGER.error(
"Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
undeletedFiles);
}
public class AbstractFactoryTemplate extends GeneralClassTemplate {
- private static final List<String> implementedIfcs = Lists
+ private static final List<String> IMPLEMENTED_IFCS = Lists
.newArrayList(ModuleFactory.class.getCanonicalName());
public AbstractFactoryTemplate(Header header, String packageName,
String abstractFactoryName,
List<Field> fields) {
super(header, packageName, abstractFactoryName, Collections
- .<String> emptyList(), implementedIfcs, fields, Collections
+ .<String> emptyList(), IMPLEMENTED_IFCS, fields, Collections
.<MethodDefinition> emptyList(), true, false, Collections
.<Constructor> emptyList());
}
.getFullyQualifiedName(rootRB.getPackageName(), rootRB.getJavaNameOfRuntimeMXBean());
String childRegistratorFQN = rootFtlFile.getFullyQualifiedName();
Field rbParameter = new Field(fullyQualifiedNameOfMXBean, "rb");
- StringBuffer registerBody = new StringBuffer();
+ StringBuilder registerBody = new StringBuilder();
registerBody.append(format("%s %s = this.%s.registerRoot(%s);\n",
HierarchicalRuntimeBeanRegistration.class
.getCanonicalName(), hierachchicalRegistration
unorderedResult.put(entry.getKey(), entry.getValue());
}
- if (childRegistratorMap.size() > 0) {
+ if (!childRegistratorMap.isEmpty()) {
// first entry is the direct descendant according to the create
// contract
RuntimeRegistratorFtlTemplate childRegistrator = childRegistratorMap
.values().iterator().next();
- StringBuffer body = new StringBuffer();
+ StringBuilder body = new StringBuilder();
String key, value;
key = child.getJavaNamePrefix();
body.append(format(
static String serializeType(Type type, boolean addWildcards) {
if (type instanceof ParameterizedType){
ParameterizedType parameterizedType = (ParameterizedType) type;
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
sb.append(parameterizedType.getRawType().getFullyQualifiedName());
sb.append(addWildcards ? "<? extends " : "<");
boolean first = true;
for (Rpc rpc : rbe.getRpcs()) {
AttributeIfc returnType = rpc.getReturnType();
- if (returnType == VoidAttribute.getInstance())
+ if (returnType == VoidAttribute.getInstance()) {
continue;
- if (returnType instanceof JavaAttribute)
+ }
+ if (returnType instanceof JavaAttribute) {
continue;
- if (returnType instanceof ListAttribute && returnType.getOpenType() instanceof SimpleType)
+ }
+ if (returnType instanceof ListAttribute && returnType.getOpenType() instanceof SimpleType) {
continue;
+ }
Preconditions.checkState(yangPropertiesToTypesMap.containsKey(returnType.getAttributeYangName()) == false,
"Duplicate TO %s for %s", returnType.getAttributeYangName(), rbe);
String returnType;
AttributeIfc attributeIfc = attrEntry.getValue();
- boolean isIdentityRef = false;
if (attributeIfc instanceof TypedAttribute) {
TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
returnType = serializeType(typedAttribute.getType());
public class ConfigConstants {
+ private ConfigConstants() {
+ }
+
public static final String CONFIG_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:config";
public static final String CONFIG_MODULE = "config";
return this;
}
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(ModuleMXBeanEntryBuilder.class);
// TODO: the XPath should be parsed by code generator IMO
private static final String MAGIC_STRING = "MAGIC_STRING";
private static final String MODULE_CONDITION_XPATH_TEMPLATE = "^/MAGIC_STRING:modules/MAGIC_STRING:module/MAGIC_STRING:type\\s*=\\s*['\"](.+)['\"]$";
- private static final SchemaPath expectedConfigurationAugmentationSchemaPath = SchemaPath.create(true,
+ private static final SchemaPath EXPECTED_CONFIGURATION_AUGMENTATION_SCHEMA_PATH = SchemaPath.create(true,
createConfigQName("modules"), createConfigQName("module"), createConfigQName("configuration"));
- private static final SchemaPath expectedStateAugmentationSchemaPath = SchemaPath.create(true,
+ private static final SchemaPath EXPECTED_STATE_AUGMENTATION_SCHEMA_PATH = SchemaPath.create(true,
createConfigQName("modules"), createConfigQName("module"), createConfigQName("state"));
private static final Pattern PREFIX_COLON_LOCAL_NAME = Pattern
.compile("^(.+):(.+)$");
public Map<String, ModuleMXBeanEntry> build() {
- logger.debug("Generating ModuleMXBeans of {} to package {}",
+ LOGGER.debug("Generating ModuleMXBeans of {} to package {}",
currentModule.getNamespace(), packageName);
String configModulePrefix;
checkAttributeNamesUniqueness(uniqueGeneratedClassesNames, result);
checkUnaugumentedIdentities(unaugmentedModuleIdentities);
- logger.debug("Number of ModuleMXBeans to be generated: {}", result.size());
+ LOGGER.debug("Number of ModuleMXBeans to be generated: {}", result.size());
return result;
}
private static void checkUnaugumentedIdentities(final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
if (unaugmentedModuleIdentities.size() > 0) {
- logger.warn("Augmentation not found for all currentModule identities: {}",
+ LOGGER.warn("Augmentation not found for all currentModule identities: {}",
unaugmentedModuleIdentities.keySet());
}
}
+ identityLocalName);
} else {
moduleIdentities.put(identityLocalName, id);
- logger.debug("Found identity {}", identityLocalName);
+ LOGGER.debug("Found identity {}", identityLocalName);
}
// validation check on unknown schema nodes
boolean providedServiceWasSet = false;
HAS_CHILDREN_AND_QNAME dataNodeContainer = getDataNodeContainer(choiceCaseNode);
- if (expectedConfigurationAugmentationSchemaPath.equals(augmentation.getTargetPath())) {
- logger.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
+ if (EXPECTED_CONFIGURATION_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
+ LOGGER.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
yangToAttributes = fillConfiguration(dataNodeContainer, currentModule, typeProviderWrapper, qNamesToSIEs,
schemaContext, packageName);
checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(), yangToAttributes);
- } else if (expectedStateAugmentationSchemaPath.equals(augmentation.getTargetPath())) {
- logger.debug("Parsing state of {}", moduleLocalNameFromXPath);
+ } else if (EXPECTED_STATE_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
+ LOGGER.debug("Parsing state of {}", moduleLocalNameFromXPath);
try {
runtimeBeans = fillRuntimeBeans(dataNodeContainer, currentModule, typeProviderWrapper, packageName,
moduleLocalNameFromXPath, javaNamePrefix);
public class ModuleUtil {
+ private ModuleUtil() {
+ }
+
public static QName getQName(final Module currentModule) {
return QName.create(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName());
}
// TODO add to PackageTranslator
private static String sanitizePackage(String namespace) {
- namespace = namespace.replace("://", ".");
- namespace = namespace.replace("/", ".");
- namespace = namespace.replace(":", ".");
- namespace = namespace.replace("-", "_");
- namespace = namespace.replace("@", ".");
- namespace = namespace.replace("$", ".");
- namespace = namespace.replace("#", ".");
- namespace = namespace.replace("'", ".");
- namespace = namespace.replace("*", ".");
- namespace = namespace.replace("+", ".");
- namespace = namespace.replace(",", ".");
- namespace = namespace.replace(";", ".");
- namespace = namespace.replace("=", ".");
- return namespace;
+ String newNamespace = namespace;
+ newNamespace = newNamespace.replace("://", ".");
+ newNamespace = newNamespace.replace("/", ".");
+ newNamespace = newNamespace.replace(":", ".");
+ newNamespace = newNamespace.replace("-", "_");
+ newNamespace = newNamespace.replace("@", ".");
+ newNamespace = newNamespace.replace("$", ".");
+ newNamespace = newNamespace.replace("#", ".");
+ newNamespace = newNamespace.replace("'", ".");
+ newNamespace = newNamespace.replace("*", ".");
+ newNamespace = newNamespace.replace("+", ".");
+ newNamespace = newNamespace.replace(",", ".");
+ newNamespace = newNamespace.replace(";", ".");
+ newNamespace = newNamespace.replace("=", ".");
+ return newNamespace;
}
}
final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
List<AttributeIfc> attributes = Lists.newArrayList();
- // List<JavaAttribute> javaAttributes = new ArrayList<>();
- // List<TOAttribute> toAttributes = new ArrayList<>();
List<RuntimeBeanEntry> runtimeBeanEntries = new ArrayList<>();
for (DataSchemaNode child : subtree.getChildNodes()) {
// child leaves can be java attributes, TO attributes, or child
.findJavaParameter(rpcDefinition);
AttributeIfc returnType;
if (rpcDefinition.getOutput() == null
- || rpcDefinition.getOutput().getChildNodes().size() == 0) {
+ || rpcDefinition.getOutput().getChildNodes().isEmpty()) {
returnType = VoidAttribute.getInstance();
} else if (rpcDefinition.getOutput().getChildNodes().size() == 1) {
DataSchemaNode returnDSN = rpcDefinition.getOutput()
currentModule, identitiesToRpcs);
Optional<String> keyYangName;
- if (listSchemaNode.getKeyDefinition().size() == 0) {
+ if (listSchemaNode.getKeyDefinition().isEmpty()) {
keyYangName = Optional.absent();
} else if (listSchemaNode.getKeyDefinition().size() == 1) {
// key must be either null or one of supported key types
* </p>
*/
public class ServiceInterfaceEntry extends AbstractEntry {
- private static final Logger logger = LoggerFactory
+ private static final Logger LOGGER = LoggerFactory
.getLogger(ServiceInterfaceEntry.class);
private static final String CLASS_NAME_SUFFIX = "ServiceInterface";
*/
public static Map<QName, ServiceInterfaceEntry> create(Module currentModule,
String packageName,Map<IdentitySchemaNode, ServiceInterfaceEntry> definedSEItracker) {
- logger.debug("Generating ServiceInterfaces from {} to package {}",
+ LOGGER.debug("Generating ServiceInterfaces from {} to package {}",
currentModule.getNamespace(), packageName);
Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
Set<IdentitySchemaNode> notVisited = new HashSet<>(
currentModule.getIdentities());
int lastSize = notVisited.size() + 1;
- while (notVisited.size() > 0) {
+ while (!notVisited.isEmpty()) {
if (notVisited.size() == lastSize) {
- logger.debug(
+ LOGGER.debug(
"Following identities will be ignored while generating ServiceInterfaces, as they are not derived from {} : {}",
SERVICE_TYPE_Q_NAME, notVisited);
break;
for (ServiceInterfaceEntry sie : identitiesToSIs.values()) {
resultMap.put(sie.getQName(), sie);
}
- logger.debug("Number of ServiceInterfaces to be generated: {}",
+ LOGGER.debug("Number of ServiceInterfaces to be generated: {}",
resultMap.size());
return resultMap;
}
@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;
+ }
ServiceInterfaceEntry that = (ServiceInterfaceEntry) o;
- if (!maybeBaseCache.equals(that.maybeBaseCache))
+ if (!maybeBaseCache.equals(that.maybeBaseCache)) {
return false;
- if (!nullableDescription.equals(that.nullableDescription))
+ }
+ if (!nullableDescription.equals(that.nullableDescription)) {
return false;
- if (!exportedOsgiClassName.equals(that.exportedOsgiClassName))
+ }
+ if (!exportedOsgiClassName.equals(that.exportedOsgiClassName)) {
return false;
- if (!qName.equals(that.qName))
+ }
+ if (!qName.equals(that.qName)) {
return false;
- if (!packageName.equals(that.packageName))
+ }
+ if (!packageName.equals(that.packageName)) {
return false;
- if (!typeName.equals(that.typeName))
+ }
+ if (!typeName.equals(that.typeName)) {
return false;
+ }
return true;
}
try {
javaType = typeProvider.javaTypeForSchemaDefinitionType(
type, leaf);
- if (javaType == null)
+ if (javaType == null) {
throw new IllegalArgumentException("Unknown type received for "
+ leaf.toString());
+ }
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Error while resolving type of "
+ leaf, e);
try {
javaType = typeProvider.javaTypeForSchemaDefinitionType(
leaf.getType(), leaf);
- if (javaType == null)
+ if (javaType == null) {
throw new IllegalArgumentException(
"Unknown type received for " + leaf.toString());
+ }
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Error while resolving type of "
+ leaf, e);
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (!(o instanceof AbstractAttribute))
+ }
+ if (!(o instanceof AbstractAttribute)) {
return false;
+ }
AbstractAttribute that = (AbstractAttribute) o;
if (attributeYangName != null ? !attributeYangName
.equals(that.attributeYangName)
- : that.attributeYangName != null)
+ : that.attributeYangName != null) {
return false;
+ }
return true;
}
@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;
- if (!super.equals(o))
+ }
+ if (!super.equals(o)) {
return false;
+ }
AbstractDependencyAttribute that = (AbstractDependencyAttribute) o;
if (dependency != null ? !dependency.equals(that.dependency)
- : that.dependency != null)
+ : that.dependency != null) {
return false;
+ }
if (nullableDefault != null ? !nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null)
+ .equals(that.nullableDefault) : that.nullableDefault != null) {
return false;
+ }
if (nullableDescription != null ? !nullableDescription
.equals(that.nullableDescription)
- : that.nullableDescription != null)
+ : that.nullableDescription != null) {
return false;
+ }
return true;
}
@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;
- if (!super.equals(o))
+ }
+ if (!super.equals(o)) {
return false;
+ }
JavaAttribute that = (JavaAttribute) o;
if (nullableDefault != null ? !nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null)
+ .equals(that.nullableDefault) : that.nullableDefault != null) {
return false;
+ }
if (nullableDescription != null ? !nullableDescription
.equals(that.nullableDescription)
- : that.nullableDescription != null)
+ : that.nullableDescription != null) {
return false;
- if (type != null ? !type.equals(that.type) : that.type != null)
+ }
+ if (type != null ? !type.equals(that.type) : that.type != null) {
return false;
+ }
return true;
}
@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;
- if (!super.equals(o))
+ }
+ if (!super.equals(o)) {
return false;
+ }
ListAttribute that = (ListAttribute) o;
if (nullableDefault != null ? !nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null)
+ .equals(that.nullableDefault) : that.nullableDefault != null) {
return false;
+ }
if (nullableDescription != null ? !nullableDescription
.equals(that.nullableDescription)
- : that.nullableDescription != null)
+ : that.nullableDescription != null) {
return false;
+ }
return true;
}
public class SimpleTypeResolver {
+ private SimpleTypeResolver() {
+ }
+
public static SimpleType<?> getSimpleType(Type type) {
SimpleType<?> expectedSimpleType = JAVA_TYPE_TO_SIMPLE_TYPE.get(type
.getFullyQualifiedName());
TypeProviderWrapper typeProviderWrapper, String packageName) {
Class<? extends DataSchemaNode> type = isAllowedType(dataSchemaNode);
- if (type.equals(LeafSchemaNode.class))
+ if (type.equals(LeafSchemaNode.class)) {
return new JavaAttribute((LeafSchemaNode) dataSchemaNode,
typeProviderWrapper);
- else if (type.equals(ListSchemaNode.class))
+ } else if (type.equals(ListSchemaNode.class)) {
return ListAttribute.create((ListSchemaNode) dataSchemaNode,
typeProviderWrapper, packageName);
- else if (type.equals(LeafListSchemaNode.class))
+ } else if (type.equals(LeafListSchemaNode.class)) {
return ListAttribute.create((LeafListSchemaNode) dataSchemaNode,
typeProviderWrapper);
- else if (type.equals(ContainerSchemaNode.class))
+ } else if (type.equals(ContainerSchemaNode.class)) {
return TOAttribute.create((ContainerSchemaNode) dataSchemaNode,
typeProviderWrapper, packageName);
+ }
throw new IllegalStateException("This should never happen");
}
private static Class<? extends DataSchemaNode> isAllowedType(
DataSchemaNode dataSchemaNode) {
for (Class<? extends DataSchemaNode> allowedType : ALLOWED_CHILDREN) {
- if (allowedType.isAssignableFrom(dataSchemaNode.getClass()) == true)
+ if (allowedType.isAssignableFrom(dataSchemaNode.getClass()) == true) {
return allowedType;
+ }
}
throw new IllegalArgumentException("Illegal child node for TO: "
+ dataSchemaNode.getClass() + " allowed node types: "
@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;
- if (!super.equals(o))
+ }
+ if (!super.equals(o)) {
return false;
+ }
TOAttribute that = (TOAttribute) o;
if (nullableDefault != null ? !nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null)
+ .equals(that.nullableDefault) : that.nullableDefault != null) {
return false;
+ }
if (nullableDescription != null ? !nullableDescription
.equals(that.nullableDescription)
- : that.nullableDescription != null)
+ : that.nullableDescription != null) {
return false;
+ }
if (yangNameToAttributeMap != null ? !yangNameToAttributeMap
.equals(that.yangNameToAttributeMap)
- : that.yangNameToAttributeMap != null)
+ : that.yangNameToAttributeMap != null) {
return false;
+ }
return true;
}
final class Util {
+ private Util() {
+ }
/**
* Used for date <-> xml serialization
*/
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
+ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd");
public static String writeDate(Date date) {
- return dateFormat.format(date);
+ return DATE_FORMAT.format(date);
}
public static Date readDate(String s) throws ParseException {
- return dateFormat.parse(s);
+ return DATE_FORMAT.parse(s);
}
}
package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
public class FullyQualifiedNameHelper {
+
+ private FullyQualifiedNameHelper() {
+ }
+
public static String getFullyQualifiedName(String packageName,
String className) {
if (packageName.isEmpty())