Fix checkstyle issues to enforce it.
Change-Id: I8ea15ab059b1ffa3de79737cf2ca0763f2455139
Signed-off-by: David Suarez <david.suarez.fuentes@gmail.com>
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <artifactId>config-subsystem</artifactId>
- <groupId>org.opendaylight.controller</groupId>
- <version>0.8.0-SNAPSHOT</version>
- </parent>
- <artifactId>config-manager-facade-xml</artifactId>
- <name>${project.artifactId}</name>
- <packaging>bundle</packaging>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>config-subsystem</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <version>0.8.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <name>${project.artifactId}</name>
+ <packaging>bundle</packaging>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>yang-jmx-generator</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-generator-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Activator>org.opendaylight.controller.config.facade.xml.osgi.YangStoreActivator</Bundle-Activator>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.opendaylight.controller.config.facade.xml.osgi.YangStoreActivator</Bundle-Activator>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
</project>
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private final Config configResolver;
private final XmlElement configElement;
- public ConfigExecution(final Config configResolver, final XmlElement configElement, final TestOption testOption, final EditStrategyType defaultStrategy) throws DocumentedException {
+ public ConfigExecution(final Config configResolver, final XmlElement configElement, final TestOption testOption,
+ final EditStrategyType defaultStrategy) throws DocumentedException {
Config.checkUnrecognisedChildren(configElement);
this.configResolver = configResolver;
this.configElement = configElement;
public Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(
final ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
- return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
+ return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType,
+ getServiceRegistryWrapper(serviceRegistry));
}
public ServiceRegistryWrapper getServiceRegistryWrapper(final ServiceReferenceReadableRegistry serviceRegistry) {
return new ServiceRegistryWrapper(serviceRegistry);
}
- public Map<String, Multimap<String,ModuleElementDefinition>> getModulesDefinition(
+ public Map<String, Multimap<String, ModuleElementDefinition>> getModulesDefinition(
final ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
- return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
+ return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType,
+ getServiceRegistryWrapper(serviceRegistry));
}
public EditStrategyType getDefaultStrategy() {
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import com.google.common.base.Optional;
import com.google.common.collect.Multimap;
+
import java.io.Closeable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
+
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.w3c.dom.Element;
/**
- * Config subsystem facade for xml format
+ * Config subsystem facade for xml format.
+ *
* <p>
* TODO extract generic interface for config subsystem facades
*/
private final ConfigRegistryClient configRegistryClientNoNotifications;
private final RpcFacade rpcFacade;
- public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient, final ConfigRegistryClient configRegistryClientNoNotifications, final YangStoreService yangStoreService, final String id) {
+ public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
+ final ConfigRegistryClient configRegistryClientNoNotifications,
+ final YangStoreService yangStoreService,
+ final String id) {
this.configRegistryClient = configRegistryClient;
this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
this.yangStoreService = yangStoreService;
rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
}
- public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient, final ConfigRegistryClient configRegistryClientNoNotifications, final YangStoreService yangStoreService, final TransactionProvider txProvider) {
+ public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
+ final ConfigRegistryClient configRegistryClientNoNotifications,
+ final YangStoreService yangStoreService,
+ final TransactionProvider txProvider) {
this.configRegistryClient = configRegistryClient;
this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
this.yangStoreService = yangStoreService;
rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
}
- public Element getConfiguration(final Document document, final Datastore source, final Optional<String> maybeNamespace) {
+ public Element getConfiguration(final Document document, final Datastore source,
+ final Optional<String> maybeNamespace) {
final ConfigTransactionClient registryClient;
- // Read current state from a transaction, if running is source, then start new transaction just for reading
+ // Read current state from a transaction, if running is source, then start new
+ // transaction just for reading
// in case of candidate, get current transaction representing candidate
if (source == Datastore.running) {
final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
registryClient = configRegistryClient.getConfigTransactionClient(readTx);
} else {
- registryClient = configRegistryClient.getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
+ registryClient = configRegistryClient
+ .getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
}
try {
- Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
+ Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY,
+ Optional.<String>absent());
final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
.queryInstances(configRegistryClient);
- final Config configMapping =
- new Config(transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()), yangStoreService.getEnumResolver());
+ final Config configMapping = new Config(
+ transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()),
+ yangStoreService.getEnumResolver());
ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
dataElement = configMapping.toXml(instances, maybeNamespace, document, dataElement, serviceTracker);
}
}
- public void executeConfigExecution(final ConfigExecution configExecution) throws DocumentedException, ValidationException {
+ public void executeConfigExecution(final ConfigExecution configExecution)
+ throws DocumentedException, ValidationException {
if (configExecution.shouldTest()) {
executeTests(configExecution);
}
}
}
- public CommitStatus commitTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
+ public CommitStatus commitTransaction()
+ throws DocumentedException, ValidationException, ConflictingVersionException {
final CommitStatus status = this.transactionProvider.commitTransaction();
LOG.trace("Transaction committed successfully: {}", status);
return status;
}
- public CommitStatus commitSilentTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
+ public CommitStatus commitSilentTransaction()
+ throws DocumentedException, ValidationException, ConflictingVersionException {
final CommitStatus status = this.transactionProvider.commitTransaction(configRegistryClientNoNotifications);
LOG.trace("Transaction committed successfully: {}", status);
return status;
private void executeSet(final ConfigExecution configExecution) throws DocumentedException {
set(configExecution);
- LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
+ LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
+ configExecution.getConfigElement());
}
private void executeTests(final ConfigExecution configExecution) throws DocumentedException, ValidationException {
test(configExecution, configExecution.getDefaultStrategy());
- LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
+ LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
+ configExecution.getConfigElement());
}
- private void test(final ConfigExecution execution, final EditStrategyType editStrategyType) throws ValidationException, DocumentedException {
+ private void test(final ConfigExecution execution, final EditStrategyType editStrategyType)
+ throws ValidationException, DocumentedException {
ObjectName taON = transactionProvider.getTestTransaction();
try {
// default strategy = replace wipes config
}
}
- private void set(final ConfigExecution ConfigExecution) throws DocumentedException {
+ private void set(final ConfigExecution configExecution) throws DocumentedException {
ObjectName taON = transactionProvider.getOrCreateTransaction();
// default strategy = replace wipes config
- if (ConfigExecution.getDefaultStrategy() == EditStrategyType.replace) {
+ if (configExecution.getDefaultStrategy() == EditStrategyType.replace) {
transactionProvider.wipeTransaction();
}
ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
- handleMisssingInstancesOnTransaction(ta, ConfigExecution);
- setServicesOnTransaction(ta, ConfigExecution);
- setOnTransaction(ta, ConfigExecution);
+ handleMisssingInstancesOnTransaction(ta, configExecution);
+ setServicesOnTransaction(ta, configExecution);
+ setOnTransaction(ta, configExecution);
}
- private void setServicesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution) throws DocumentedException {
-
+ private void setServicesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
+ throws DocumentedException {
Services services = execution.getServices();
- Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = services
- .getNamespaceToServiceNameToRefNameToInstance();
-
- for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance.entrySet()) {
- for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry : namespaceToServiceToRefEntry.getValue().entrySet()) {
+ Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance =
+ services.getNamespaceToServiceNameToRefNameToInstance();
+ for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>>
+ namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance
+ .entrySet()) {
+ for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry
+ : namespaceToServiceToRefEntry.getValue().entrySet()) {
String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
try {
if (Services.ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
- LOG.debug("Removing service {} with name {}", qnameOfService, refNameToServiceEntry.getKey());
+ LOG.debug("Removing service {} with name {}", qnameOfService,
+ refNameToServiceEntry.getKey());
} else {
- ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(), on);
+ ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(),
+ on);
LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
on, refNameToServiceEntry.getKey(), saved);
}
} catch (final InstanceNotFoundException e) {
- throw new DocumentedException(String.format("Unable to edit ref name " + refNameToServiceEntry.getKey() + " for instance " + on, e),
- ErrorType.APPLICATION,
- ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR);
+ throw new DocumentedException(
+ String.format("Unable to edit ref name " + refNameToServiceEntry.getKey()
+ + " for instance " + on, e),
+ ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
}
}
}
return ta.getServiceInterfaceName(namespace, serviceName);
}
- private void setOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution) throws DocumentedException {
+ private void setOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
+ throws DocumentedException {
- for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
+ for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta)
+ .values()) {
for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
String moduleName = moduleToResolved.getKey();
InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
EditConfigStrategy strategy = ice.getEditStrategy();
- strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta, execution.getServiceRegistryWrapper(ta));
+ strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta,
+ execution.getServiceRegistryWrapper(ta));
}
}
}
- private void handleMisssingInstancesOnTransaction(final ConfigTransactionClient ta,
- final ConfigExecution execution) throws DocumentedException {
+ private void handleMisssingInstancesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
+ throws DocumentedException {
- for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
+ for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta)
+ .values()) {
for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
String moduleName = moduleToResolved.getKey();
ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
- strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta));
+ strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta,
+ execution.getServiceRegistryWrapper(ta));
}
}
}
public Config getConfigMapping() {
final YangStoreContext snapshot = yangStoreService.getCurrentSnapshot();
- Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(snapshot.getModuleMXBeanEntryMap());
+ Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(
+ snapshot.getModuleMXBeanEntryMap());
Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(snapshot.getModules());
return new Config(factories, identitiesMap, snapshot.getEnumResolver());
}
Map<String, Map<Date, IdentityMapping>> mappedIds = new HashMap<>();
for (Module module : modules) {
String namespace = module.getNamespace().toString();
- Map<Date, IdentityMapping> revisionsByNamespace =
- mappedIds.computeIfAbsent(namespace, k -> new HashMap<>());
+ Map<Date, IdentityMapping> revisionsByNamespace = mappedIds.computeIfAbsent(namespace,
+ k -> new HashMap<>());
Date revision = module.getRevision();
- IdentityMapping identityMapping =
- revisionsByNamespace.computeIfAbsent(revision, k -> new IdentityMapping());
+ IdentityMapping identityMapping = revisionsByNamespace.computeIfAbsent(revision,
+ k -> new IdentityMapping());
for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
identityMapping.addIdSchemaNode(identitySchemaNode);
}
public Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(
+ Map<String /* Name of module entry from yang file */,
+ ModuleConfig>> transformMbeToModuleConfigs(
final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
- return transformMbeToModuleConfigs(configRegistryClient, mBeanEntries);
+ Map<String /* Name of module entry from yang file */,
+ ModuleMXBeanEntry>> mbeanentries) {
+ return transformMbeToModuleConfigs(configRegistryClient, mbeanentries);
}
public Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(
+ Map<String /* Name of module entry from yang file */,
+ ModuleConfig>> transformMbeToModuleConfigs(
final BeanReader reader,
- final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
-
+ final Map<String/* Namespace from yang file */,
+ Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mbeanentries) {
Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = new HashMap<>();
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mBeanEntries.entrySet()) {
+ for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mbeanentries.entrySet()) {
for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
String moduleName = moduleNameToMbe.getKey();
ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
- ModuleConfig moduleConfig = new ModuleConfig(moduleName,
- new InstanceConfig(reader, moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
+ ModuleConfig moduleConfig = new ModuleConfig(moduleName, new InstanceConfig(reader,
+ moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
- Map<String, ModuleConfig> moduleNameToModuleConfig =
- namespaceToModuleNameToModuleConfig.computeIfAbsent(namespaceToModuleToMbe.getKey(),
- k -> new HashMap<>());
+ Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig
+ .computeIfAbsent(namespaceToModuleToMbe.getKey(), k -> new HashMap<>());
moduleNameToModuleConfig.put(moduleName, moduleConfig);
}
return namespaceToModuleNameToModuleConfig;
}
- public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted) throws DocumentedException {
- return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet, EditStrategyType.getDefaultStrategy());
+ public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted)
+ throws DocumentedException {
+ return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet,
+ EditStrategyType.getDefaultStrategy());
}
- private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(final ConfigRegistryClient configRegistryClient,
- final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
+ private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(
+ final ConfigRegistryClient configRegistryClient,
+ final Map<String, Map<String, ModuleMXBeanEntry>> mbeanentries) {
Map<String, Map<String, ModuleRuntime>> retVal = new HashMap<>();
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mBeanEntries.entrySet()) {
+ for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mbeanentries.entrySet()) {
Map<String, ModuleRuntime> innerMap = new HashMap<>();
Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
Map<RuntimeBeanEntry, InstanceConfig> cache = new HashMap<>();
RuntimeBeanEntry root = null;
for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
- cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(), mbe.getNullableDummyContainerName()));
+ cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(),
+ mbe.getNullableDummyContainerName()));
if (rbe.isRoot()) {
root = rbe;
}
return retVal;
}
- private InstanceRuntime createInstanceRuntime(final RuntimeBeanEntry root, final Map<RuntimeBeanEntry, InstanceConfig> cache) {
+ private InstanceRuntime createInstanceRuntime(final RuntimeBeanEntry root,
+ final Map<RuntimeBeanEntry, InstanceConfig> cache) {
Map<String, InstanceRuntime> children = new HashMap<>();
for (RuntimeBeanEntry child : root.getChildren()) {
children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
final ConfigTransactionClient txClient = configRegistryClient.getConfigTransactionClient(testTransaction);
try {
- // Runtime beans are not parts of transactions and have to be queried against the central registry
+ // Runtime beans are not parts of transactions and have to be queried against
+ // the central registry
final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
- final Set<ObjectName> configBeans = Datastore.getInstanceQueryStrategy(Datastore.running, transactionProvider)
+ final Set<ObjectName> configBeans = Datastore
+ .getInstanceQueryStrategy(Datastore.running, transactionProvider)
.queryInstances(configRegistryClient);
final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
final Map<String, Map<String, ModuleConfig>> moduleConfigs = transformMbeToModuleConfigs(txClient,
yangStoreSnapshot.getModuleMXBeanEntryMap());
- final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes, moduleConfigs);
+ final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes,
+ moduleConfigs);
return runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
} finally {
}
}
-
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class ConfigSubsystemFacadeFactory {
- private ConfigRegistryClient cfgRegClient;
- private ConfigRegistryJMXClient cfgRegClientNoNotifications;
- private YangStoreService yangStoreService;
+ private final ConfigRegistryClient cfgRegClient;
+ private final ConfigRegistryJMXClient cfgRegClientNoNotifications;
+ private final YangStoreService yangStoreService;
- public ConfigSubsystemFacadeFactory(final ConfigRegistryClient cfgRegClient, final ConfigRegistryJMXClient jmxClientNoNotifications, final YangStoreService yangStoreService) {
+ public ConfigSubsystemFacadeFactory(final ConfigRegistryClient cfgRegClient,
+ final ConfigRegistryJMXClient jmxClientNoNotifications, final YangStoreService yangStoreService) {
this.cfgRegClient = cfgRegClient;
this.cfgRegClientNoNotifications = jmxClientNoNotifications;
this.yangStoreService = yangStoreService;
}
/**
- * Create new instance of ConfigSubsystemFacade. Each instance works with a dedicated transaction provider, making
- * the instances suitable for facade-per-client use.
+ * Create new instance of ConfigSubsystemFacade. Each instance works with a
+ * dedicated transaction provider, making the instances suitable for
+ * facade-per-client use.
*/
public ConfigSubsystemFacade createFacade(final String id) {
return new ConfigSubsystemFacade(cfgRegClient, cfgRegClientNoNotifications, yangStoreService, id);
for (Module module : modules) {
capabilities.add(new YangModuleCapability(module, yangStoreService.getModuleSource(module)));
}
-
return capabilities;
}
-
-
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
running, candidate;
- /**
- * @param source
- * @param transactionProvider
- * @return
- */
public static DatastoreQueryStrategy getInstanceQueryStrategy(final Datastore source,
final TransactionProvider transactionProvider) {
switch (source) {
- case running:
- return new RunningDatastoreQueryStrategy(transactionProvider);
- case candidate:
- return new CandidateDatastoreQueryStrategy(transactionProvider);
- default:
- throw new UnsupportedOperationException("Unimplemented datastore query strategy for " + source);
+ case running:
+ return new RunningDatastoreQueryStrategy(transactionProvider);
+ case candidate:
+ return new CandidateDatastoreQueryStrategy(transactionProvider);
+ default:
+ throw new UnsupportedOperationException("Unimplemented datastore query strategy for " + source);
}
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.controller.config.util.ConfigRegistryClient;
public interface DatastoreQueryStrategy {
-
- /**
- * @param configRegistryClient
- * @return
- */
Set<ObjectName> queryInstances(ConfigRegistryClient configRegistryClient);
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class RpcFacade {
public static final String CONTEXT_INSTANCE = "context-instance";
- private YangStoreService yangStoreService;
- private ConfigRegistryClient configRegistryClient;
+ private final YangStoreService yangStoreService;
+ private final ConfigRegistryClient configRegistryClient;
public RpcFacade(final YangStoreService yangStoreService, final ConfigRegistryClient configRegistryClient) {
this.yangStoreService = yangStoreService;
final Map<String, Map<String, ModuleRpcs>> map = new HashMap<>();
- for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService.getModuleMXBeanEntryMap().entrySet()) {
+ for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService
+ .getModuleMXBeanEntryMap().entrySet()) {
- Map<String, ModuleRpcs> namespaceToModules =
- map.computeIfAbsent(namespaceToModuleEntry.getKey(), k -> new HashMap<>());
+ Map<String, ModuleRpcs> namespaceToModules = map.computeIfAbsent(namespaceToModuleEntry.getKey(),
+ k -> new HashMap<>());
- for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue().entrySet()) {
+ for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue()
+ .entrySet()) {
ModuleRpcs rpcMapping = namespaceToModules.computeIfAbsent(moduleEntry.getKey(),
- k -> new ModuleRpcs(yangStoreService.getEnumResolver()));
+ k -> new ModuleRpcs(yangStoreService.getEnumResolver()));
final ModuleMXBeanEntry entry = moduleEntry.getValue();
return new Rpcs(map);
}
-
public OperationExecution fromXml(final XmlElement xml) throws DocumentedException {
final String namespace;
namespace = xml.getNamespace();
final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
final String operationName = xml.getName();
- final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(
- contextInstanceElement.getTextContent(), operationName, namespace);
+ final RuntimeRpcElementResolved id = RuntimeRpcElementResolved
+ .fromXpath(contextInstanceElement.getTextContent(), operationName, namespace);
final Rpcs rpcs = mapRpcs();
Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
attributes = sortAttributes(attributes, xml);
- return new OperationExecution(on, instanceRuntimeRpc.getName(), attributes,
- instanceRuntimeRpc.getReturnType(), namespace);
+ return new OperationExecution(on, instanceRuntimeRpc.getName(), attributes, instanceRuntimeRpc.getReturnType(),
+ namespace);
}
- private Map<String, AttributeConfigElement> sortAttributes(
- final Map<String, AttributeConfigElement> attributes, final XmlElement xml) {
+ private Map<String, AttributeConfigElement> sortAttributes(final Map<String, AttributeConfigElement> attributes,
+ final XmlElement xml) {
final Map<String, AttributeConfigElement> sorted = new LinkedHashMap<>();
for (XmlElement xmlElement : xml.getChildElements()) {
final Object[] params = new Object[execution.attributes.size()];
final String[] signature = new String[execution.attributes.size()];
- int i = 0;
+ int index = 0;
for (final AttributeConfigElement attribute : execution.attributes.values()) {
final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
- params[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
- signature[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName() : attribute
- .getResolvedDefaultValue().getClass().getName();
- i++;
+ params[index] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
+ signature[index] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName()
+ : attribute.getResolvedDefaultValue().getClass().getName();
+ index++;
}
return configRegistryClient.invokeMethod(execution.on, execution.operationName, params, signature);
}
- public Element toXml(final Document doc, final Object result, final OperationExecution execution) throws DocumentedException {
- AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper().prepareStrategy(execution.getReturnType());
+ public Element toXml(final Document doc, final Object result, final OperationExecution execution)
+ throws DocumentedException {
+ AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper()
+ .prepareStrategy(execution.getReturnType());
Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
- Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, execution.getReturnType().getOpenType());
+ Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result,
+ execution.getReturnType().getOpenType());
- // FIXME: multiple return values defined as leaf-list and list in yang should not be wrapped in output xml element,
+ // FIXME: multiple return values defined as leaf-list and list in yang should
+ // not be wrapped in output xml element,
// they need to be appended directly under rpc-reply element
//
// Either allow List of Elements to be returned from NetconfOperation or
// pass reference to parent output xml element for netconf operations to
// append result(s) on their own
- Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ Element tempParent = XmlUtil.createElement(doc, "output",
+ Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
new ObjectXmlWriter().prepareWritingStrategy(execution.getReturnType().getAttributeYangName(),
- execution.getReturnType(), doc).writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get());
+ execution.getReturnType(), doc)
+ .writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get());
XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
private final String namespace;
public OperationExecution(final ObjectName on, final String name,
- final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType, final String namespace) {
+ final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType,
+ final String namespace) {
this.on = on;
this.operationName = name;
this.attributes = attributes;
return namespace;
}
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public static TestOption getFromXmlName(final String testOptionXmlName) {
switch (testOptionXmlName) {
- case "test-only":
- return testOnly;
- case "test-then-set":
- return testThenSet;
- case "set":
- return set;
- default:
- throw new IllegalArgumentException("Unsupported test option " + testOptionXmlName + " supported: "
- + Arrays.toString(TestOption.values()));
+ case "test-only":
+ return testOnly;
+ case "test-then-set":
+ return testThenSet;
+ case "set":
+ return set;
+ default:
+ throw new IllegalArgumentException("Unsupported test option " + testOptionXmlName + " supported: "
+ + Arrays.toString(TestOption.values()));
}
}
public static TestOption getDefault() {
return testThenSet;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private static final long serialVersionUID = 1L;
public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
+ final ErrorSeverity errorSeverity) {
this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
}
public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
- super(message,errorType,errorTag,errorSeverity,errorInfo);
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private static final long serialVersionUID = 1L;
public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
}
public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
- super(message,errorType,errorTag,errorSeverity,errorInfo);
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
if (attributeIfc instanceof JavaAttribute) {
try {
- if(((JavaAttribute)attributeIfc).getTypeDefinition() instanceof BinaryTypeDefinition) {
+ if (((JavaAttribute) attributeIfc).getTypeDefinition() instanceof BinaryTypeDefinition) {
return caseJavaBinaryAttribute(openType);
- } else if(((JavaAttribute)attributeIfc).isUnion()) {
+ } else if (((JavaAttribute) attributeIfc).isUnion()) {
return caseJavaUnionAttribute(openType);
- } else if(((JavaAttribute)attributeIfc).isIdentityRef()) {
+ } else if (((JavaAttribute) attributeIfc).isIdentityRef()) {
return caseJavaIdentityRefAttribute(openType);
- } else if(((JavaAttribute)attributeIfc).isEnum()) {
+ } else if (((JavaAttribute) attributeIfc).isEnum()) {
return caseJavaEnumAttribute(openType);
} else {
return caseJavaAttribute(openType);
private static class UnknownOpenTypeException extends RuntimeException {
private static final long serialVersionUID = 1L;
- public UnknownOpenTypeException(final String message) {
+ UnknownOpenTypeException(final String message) {
super(message);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
public AttributeConfigElement readElement(final List<XmlElement> configNodes) throws DocumentedException {
- if (configNodes.size() == 0){
+ if (configNodes.isEmpty()) {
return AttributeConfigElement.createNullValue(postprocessNullableDefault(nullableDefault));
}
return readElementHook(configNodes);
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
List<Object> innerList = Lists.newArrayList();
- EditStrategyType innerEditStrategy= null;
+ EditStrategyType innerEditStrategy = null;
for (XmlElement configNode : configNodes) {
- final AttributeConfigElement attributeConfigElement = innerStrategy.readElement(Lists.newArrayList(configNode));
- if(attributeConfigElement.getEditStrategy().isPresent()) {
+ final AttributeConfigElement attributeConfigElement = innerStrategy
+ .readElement(Lists.newArrayList(configNode));
+ if (attributeConfigElement.getEditStrategy().isPresent()) {
// TODO this sets the last operation for the entire array
innerEditStrategy = attributeConfigElement.getEditStrategy().get();
}
innerList.add(attributeConfigElement.getValue());
}
- return innerEditStrategy == null ? AttributeConfigElement.create(getNullableDefault(), innerList) :
- AttributeConfigElement.create(getNullableDefault(), innerList, innerEditStrategy);
+ return innerEditStrategy == null ? AttributeConfigElement.create(getNullableDefault(), innerList)
+ : AttributeConfigElement.create(getNullableDefault(), innerList, innerEditStrategy);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private Object resolvedDefaultValue;
private String jmxName;
- public AttributeConfigElement(final Object defaultValue, final Object value, final EditStrategyType editStrategyType) {
+ public AttributeConfigElement(final Object defaultValue, final Object value,
+ final EditStrategyType editStrategyType) {
this.defaultValue = defaultValue;
this.value = value;
this.editStrategy = Optional.fromNullable(editStrategyType);
return new AttributeConfigElement(nullableDefault, value, null);
}
- public static AttributeConfigElement createNullValue(final Object nullableDefault) {
- return new AttributeConfigElement(nullableDefault, null, null);
+ public static AttributeConfigElement create(final String nullableDefault, final Object value,
+ final EditStrategyType editStrategyType) {
+ return new AttributeConfigElement(nullableDefault, value, editStrategyType);
}
- public static AttributeConfigElement create(final String nullableDefault, final Object value, final EditStrategyType editStrategyType) {
- return new AttributeConfigElement(nullableDefault, value, editStrategyType);
+ public static AttributeConfigElement createNullValue(final Object nullableDefault) {
+ return new AttributeConfigElement(nullableDefault, null, null);
}
public Object getValue() {
public String toString() {
return "AttributeConfigElement [defaultValue=" + defaultValue + ", value=" + value + "]";
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
List<XmlElement> recognisedChildren = Lists.newArrayList();
for (Entry<String, AttributeReadingStrategy> innerAttrEntry : innerStrategies.entrySet()) {
- List<XmlElement> childItem = complexElement.getChildElementsWithSameNamespace(
- innerAttrEntry.getKey());
+ List<XmlElement> childItem = complexElement.getChildElementsWithSameNamespace(innerAttrEntry.getKey());
recognisedChildren.addAll(childItem);
AttributeConfigElement resolvedInner = innerAttrEntry.getValue().readElement(childItem);
Object value = resolvedInner.getValue();
- if(value == null) {
+ if (value == null) {
value = resolvedInner.getDefaultValue();
}
String perInstanceEditStrategy = complexElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- return Strings.isNullOrEmpty(perInstanceEditStrategy) ? AttributeConfigElement.create(getNullableDefault(), innerMap) :
- AttributeConfigElement.create(getNullableDefault(), innerMap, EditStrategyType.valueOf(perInstanceEditStrategy));
+ return Strings.isNullOrEmpty(perInstanceEditStrategy)
+ ? AttributeConfigElement.create(getNullableDefault(), innerMap)
+ : AttributeConfigElement.create(getNullableDefault(), innerMap,
+ EditStrategyType.valueOf(perInstanceEditStrategy));
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
XmlElement firstChild = configNodes.get(0);
- Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + firstChild
- + " but was " + configNodes.size());
+ Preconditions.checkState(configNodes.size() == 1,
+ "This element should be present only once " + firstChild + " but was " + configNodes.size());
Preconditions.checkNotNull(firstChild, "Element %s should be present", firstChild);
return AttributeConfigElement.create(getNullableDefault(), resolve(firstChild));
}
- private ObjectNameAttributeMappingStrategy.MappedDependency resolve(final XmlElement firstChild) throws DocumentedException{
+ private ObjectNameAttributeMappingStrategy.MappedDependency resolve(final XmlElement firstChild)
+ throws DocumentedException {
XmlElement typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
Map.Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
dependencyName);
}
- public static String checkPrefixAndExtractServiceName(final XmlElement typeElement, final Map.Entry<String, String> prefixNamespace) throws DocumentedException {
+ public static String checkPrefixAndExtractServiceName(final XmlElement typeElement,
+ final Map.Entry<String, String> prefixNamespace) throws DocumentedException {
String serviceName = typeElement.getTextContent();
Preconditions.checkNotNull(prefixNamespace.getKey(), "Service %s value cannot be linked to namespace",
XmlMappingConstants.TYPE_KEY);
- if(prefixNamespace.getKey().isEmpty()) {
+ if (prefixNamespace.getKey().isEmpty()) {
return serviceName;
} else {
String prefix = prefixNamespace.getKey() + PREFIX_SEPARATOR;
return serviceName;
}
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private String key;
private Map<String, Map<Date, IdentityMapping>> identityMap;
- public Map<String, AttributeReadingStrategy> prepareReading(final Map<String, AttributeIfc> yangToAttrConfig, final Map<String, Map<Date, IdentityMapping>> identityMap) {
+ public Map<String, AttributeReadingStrategy> prepareReading(final Map<String, AttributeIfc> yangToAttrConfig,
+ final Map<String, Map<Date, IdentityMapping>> identityMap) {
Map<String, AttributeReadingStrategy> strategies = Maps.newHashMap();
this.identityMap = identityMap;
@Override
public AttributeReadingStrategy caseJavaArrayAttribute(final ArrayType<?> openType) {
- SimpleAttributeReadingStrategy innerStrategy = new SimpleAttributeReadingStrategy(getLastAttribute().getNullableDefault());
+ SimpleAttributeReadingStrategy innerStrategy = new SimpleAttributeReadingStrategy(
+ getLastAttribute().getNullableDefault());
return new ArrayAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategy);
}
@Override
public AttributeReadingStrategy caseJavaCompositeAttribute(final CompositeType openType) {
- Preconditions.checkState(openType.keySet().size() == 1, "Unexpected number of elements for open type %s, should be 1", openType);
+ Preconditions.checkState(openType.keySet().size() == 1,
+ "Unexpected number of elements for open type %s, should be 1", openType);
String mappingKey = openType.keySet().iterator().next();
return new SimpleCompositeAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey);
}
protected AttributeReadingStrategy caseJavaIdentityRefAttribute(final OpenType<?> openType) {
Preconditions.checkState(openType instanceof CompositeType);
Set<String> keys = ((CompositeType) openType).keySet();
- Preconditions.checkState(keys.size() == 1, "Unexpected number of elements for open type %s, should be 1", openType);
+ Preconditions.checkState(keys.size() == 1, "Unexpected number of elements for open type %s, should be 1",
+ openType);
String mappingKey = keys.iterator().next();
- return new SimpleIdentityRefAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey, identityMap);
+ return new SimpleIdentityRefAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey,
+ identityMap);
}
@Override
protected AttributeReadingStrategy caseTOAttribute(final CompositeType openType) {
AttributeIfc lastAttribute = getLastAttribute();
Preconditions.checkState(lastAttribute instanceof TOAttribute);
- Map<String, AttributeIfc> inner = ((TOAttribute)lastAttribute).getYangPropertiesToTypesMap();
+ Map<String, AttributeIfc> inner = ((TOAttribute) lastAttribute).getYangPropertiesToTypesMap();
Map<String, AttributeReadingStrategy> innerStrategies = Maps.newHashMap();
innerAttrEntry.getValue());
innerStrategies.put(innerAttrEntry.getKey(), innerStrat);
}
-
return new CompositeAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategies);
}
protected AttributeReadingStrategy caseListAttribute(final ArrayType<?> openType) {
AttributeIfc lastAttribute = getLastAttribute();
Preconditions.checkState(lastAttribute instanceof ListAttribute);
- AttributeReadingStrategy innerStrategy = prepareReadingStrategy(key, ((ListAttribute) lastAttribute).getInnerAttribute());
+ AttributeReadingStrategy innerStrategy = prepareReadingStrategy(key,
+ ((ListAttribute) lastAttribute).getInnerAttribute());
return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
}
AttributeReadingStrategy innerStrategy = caseDependencyAttribute(SimpleType.OBJECTNAME);
return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.yangtools.yang.common.QName;
-
public class SimpleIdentityRefAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
private final String key;
private final Map<String, Map<Date, IdentityMapping>> identityMap;
- public SimpleIdentityRefAttributeReadingStrategy(final String nullableDefault, final String key, final Map<String, Map<Date, IdentityMapping>> identityMap) {
+ public SimpleIdentityRefAttributeReadingStrategy(final String nullableDefault, final String key,
+ final Map<String, Map<Date, IdentityMapping>> identityMap) {
super(nullableDefault);
this.key = key;
this.identityMap = identityMap;
final String namespace;
final String localName;
- if(namespaceOfTextContent.getKey().isEmpty()) {
+ if (namespaceOfTextContent.getKey().isEmpty()) {
localName = content;
namespace = xmlElement.getNamespace();
} else {
String prefix = namespaceOfTextContent.getKey() + ":";
- Preconditions.checkArgument(content.startsWith(prefix), "Identity ref should be prefixed with \"%s\"", prefix);
+ Preconditions.checkArgument(content.startsWith(prefix), "Identity ref should be prefixed with \"%s\"",
+ prefix);
localName = content.substring(prefix.length());
namespace = namespaceOfTextContent.getValue();
}
Date revision = null;
Map<Date, IdentityMapping> revisions = identityMap.get(namespace);
- if(revisions.keySet().size() > 1) {
+ if (revisions.keySet().size() > 1) {
for (Map.Entry<Date, IdentityMapping> revisionToIdentityEntry : revisions.entrySet()) {
- if(revisionToIdentityEntry.getValue().containsIdName(localName)) {
- Preconditions.checkState(revision == null, "Duplicate identity %s, in namespace %s, with revisions: %s, %s detected. Cannot map attribute",
+ if (revisionToIdentityEntry.getValue().containsIdName(localName)) {
+ Preconditions.checkState(revision == null,
+ "Duplicate identity %s, in namespace %s, "
+ + "with revisions: %s, %s detected. Cannot map attribute",
localName, namespace, revision, revisionToIdentityEntry.getKey());
revision = revisionToIdentityEntry.getKey();
}
@Override
protected Object postprocessParsedValue(final String textContent) {
- HashMap<String,String> map = Maps.newHashMap();
+ HashMap<String, String> map = Maps.newHashMap();
map.put(key, textContent);
return map;
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
public Optional<List<Object>> mapAttribute(final Object value) {
- if (value == null){
+ if (value == null) {
return Optional.absent();
}
Object innerValue = Array.get(value, i);
Optional<?> mapAttribute = innerElementStrategy.mapAttribute(innerValue);
- if (mapAttribute.isPresent()){
+ if (mapAttribute.isPresent()) {
retVal.add(mapAttribute.get());
}
}
-
return Optional.of(retVal);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
O getOpenType();
- Optional<T> mapAttribute(Object o);
-
+ Optional<T> mapAttribute(Object object);
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import javax.management.openmbean.OpenType;
import org.opendaylight.controller.config.facade.xml.util.Util;
-public class CompositeAttributeMappingStrategy extends
- AbstractAttributeMappingStrategy<Map<String, Object>, CompositeType> {
+public class CompositeAttributeMappingStrategy
+ extends AbstractAttributeMappingStrategy<Map<String, Object>, CompositeType> {
private final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies;
private final Map<String, String> jmxToJavaNameMapping;
@Override
public Optional<Map<String, Object>> mapAttribute(final Object value) {
- if (value == null){
+ if (value == null) {
return Optional.absent();
}
for (String jmxName : jmxToJavaNameMapping.keySet()) {
Optional<?> mapped = mapInnerAttribute(compositeData, jmxName, expectedType.getDescription(jmxName));
- if(mapped.isPresent()){
+ if (mapped.isPresent()) {
retVal.put(jmxToJavaNameMapping.get(jmxName), mapped.get());
}
}
return Optional.of(retVal);
}
- protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName, final String description) {
+ protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName,
+ final String description) {
Object innerValue = compositeData.get(jmxName);
- AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies
- .get(jmxName);
+ AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies.get(jmxName);
return attributeMappingStrategy.mapAttribute(innerValue);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
public Optional<String> mapAttribute(final Object value) {
- if (value == null){
+ if (value == null) {
return Optional.absent();
}
String expectedClass = getOpenType().getTypeName();
return Optional.of(enumResolver.toYang(expectedClass, value.toString()));
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
for (Entry<String, AttributeIfc> attrEntry : configDefinition.entrySet()) {
strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue()));
}
-
return strategies;
}
public AttributeMappingStrategy<?, ? extends OpenType<?>> prepareStrategy(final AttributeIfc attributeIfc) {
- if(attributeIfc instanceof DependencyAttribute) {
- namespaceOfDepAttr = ((DependencyAttribute)attributeIfc).getDependency().getSie().getQName().getNamespace().toString();
+ if (attributeIfc instanceof DependencyAttribute) {
+ namespaceOfDepAttr = ((DependencyAttribute) attributeIfc).getDependency().getSie().getQName().getNamespace()
+ .toString();
} else if (attributeIfc instanceof ListDependenciesAttribute) {
- namespaceOfDepAttr = ((ListDependenciesAttribute)attributeIfc).getDependency().getSie().getQName().getNamespace().toString();
+ namespaceOfDepAttr = ((ListDependenciesAttribute) attributeIfc).getDependency().getSie().getQName()
+ .getNamespace().toString();
}
-
return switchAttribute(attributeIfc);
}
private Map<String, String> createJmxToYangMapping(final TOAttribute attributeIfc) {
Map<String, String> retVal = Maps.newHashMap();
for (Entry<String, AttributeIfc> entry : attributeIfc.getJmxPropertiesToTypesMap().entrySet()) {
- retVal.put(entry.getKey(), (entry.getValue()).getAttributeYangName());
+ retVal.put(entry.getKey(), entry.getValue().getAttributeYangName());
}
return retVal;
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaEnumAttribute(final OpenType<?> openType) {
- return new EnumAttributeMappingStrategy(((CompositeType) openType), enumResolver);
+ return new EnumAttributeMappingStrategy((CompositeType) openType, enumResolver);
}
@Override
}
@Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(final CompositeType openType) {
+ protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(
+ final CompositeType openType) {
Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
Map<String, String> attributeMapping = Maps.newHashMap();
innerStrategies.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey)));
attributeMapping.put(innerAttributeKey, innerAttributeKey);
}
-
return new CompositeAttributeMappingStrategy(openType, innerStrategies, attributeMapping);
}
innerStrategies.put(innerAttributeKey, caseJavaAttribute(compositeType.getType(innerAttributeKey)));
attributeMapping.put(innerAttributeKey, innerAttributeKey);
}
-
return new UnionCompositeAttributeMappingStrategy(compositeType, innerStrategies, attributeMapping);
}
private String namespaceOfDepAttr;
@Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(
- final SimpleType<?> openType) {
+ protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(final SimpleType<?> openType) {
return new ObjectNameAttributeMappingStrategy(openType, namespaceOfDepAttr);
}
Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
TOAttribute lastTO = (TOAttribute) getLastAttribute();
- for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute)getLastAttribute()).getJmxPropertiesToTypesMap().entrySet()) {
+ for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute())
+ .getJmxPropertiesToTypesMap().entrySet()) {
innerStrategies.put(innerAttrEntry.getKey(), prepareStrategy(innerAttrEntry.getValue()));
}
- return new CompositeAttributeMappingStrategy(openType, innerStrategies,
- createJmxToYangMapping(lastTO));
+ return new CompositeAttributeMappingStrategy(openType, innerStrategies, createJmxToYangMapping(lastTO));
}
@Override
}
@Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(final ArrayType<?> openType) {
+ protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(
+ final ArrayType<?> openType) {
Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
return new ArrayAttributeMappingStrategy(openType, caseDependencyAttribute(SimpleType.OBJECTNAME));
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.controller.config.facade.xml.util.Util;
import org.opendaylight.yangtools.yang.common.QName;
-public class ObjectNameAttributeMappingStrategy extends
- AbstractAttributeMappingStrategy<ObjectNameAttributeMappingStrategy.MappedDependency, SimpleType<?>> {
+public class ObjectNameAttributeMappingStrategy
+ extends AbstractAttributeMappingStrategy<ObjectNameAttributeMappingStrategy.MappedDependency, SimpleType<?>> {
private final String namespace;
@Override
public Optional<MappedDependency> mapAttribute(final Object value) {
- if (value == null){
+ if (value == null) {
return Optional.absent();
}
String expectedClass = getOpenType().getClassName();
String realClass = value.getClass().getName();
- Preconditions.checkArgument(realClass.equals(expectedClass), "Type mismatch, expected " + expectedClass
- + " but was " + realClass);
+ Preconditions.checkArgument(realClass.equals(expectedClass),
+ "Type mismatch, expected " + expectedClass + " but was " + realClass);
Util.checkType(value, ObjectName.class);
ObjectName on = (ObjectName) value;
String refName = ObjectNameUtil.getReferenceName(on);
- //we want to use the exact service name that was configured in xml so services that are referencing it can be resolved
+ // we want to use the exact service name that was configured in xml so services
+ // that are referencing it can be resolved
return Optional.of(new MappedDependency(namespace,
QName.create(ObjectNameUtil.getServiceQName(on)).getLocalName(), refName));
}
public static class MappedDependency {
- private final String namespace, serviceName, refName;
+ private final String namespace;
+ private final String serviceName;
+ private final String refName;
public MappedDependency(final String namespace, final String serviceName, final String refName) {
this.serviceName = serviceName;
return sb.toString();
}
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
public Optional<String> mapAttribute(final Object value) {
- if (value == null){
+ if (value == null) {
return Optional.absent();
}
String expectedClass = getOpenType().getClassName();
String realClass = value.getClass().getName();
- Preconditions.checkArgument(realClass.equals(expectedClass), "Type mismatch, expected " + expectedClass
- + " but was " + realClass);
+ Preconditions.checkArgument(realClass.equals(expectedClass),
+ "Type mismatch, expected " + expectedClass + " but was " + realClass);
- WriterPlugin prefferedPlugin = writerPlugins.get(value.getClass().getCanonicalName());
- prefferedPlugin = prefferedPlugin == null ? writerPlugins.get(DEFAULT_WRITER_PLUGIN) : prefferedPlugin;
+ WriterPlugin prefferedPlugin = WRITER_PLUGINS.get(value.getClass().getCanonicalName());
+ prefferedPlugin = prefferedPlugin == null ? WRITER_PLUGINS.get(DEFAULT_WRITER_PLUGIN) : prefferedPlugin;
return Optional.of(prefferedPlugin.writeObject(value));
}
private static final String DEFAULT_WRITER_PLUGIN = "default";
- private static final Map<String, WriterPlugin> writerPlugins = Maps.newHashMap();
+ private static final Map<String, WriterPlugin> WRITER_PLUGINS = Maps.newHashMap();
+
static {
- writerPlugins.put(DEFAULT_WRITER_PLUGIN, new DefaultWriterPlugin());
- writerPlugins.put(Date.class.getCanonicalName(), new DatePlugin());
+ WRITER_PLUGINS.put(DEFAULT_WRITER_PLUGIN, new DefaultWriterPlugin());
+ WRITER_PLUGINS.put(Date.class.getCanonicalName(), new DatePlugin());
}
/**
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import javax.management.openmbean.OpenType;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-public class UnionCompositeAttributeMappingStrategy extends
- CompositeAttributeMappingStrategy {
+public class UnionCompositeAttributeMappingStrategy extends CompositeAttributeMappingStrategy {
-
- public UnionCompositeAttributeMappingStrategy(final CompositeType compositeType, final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies, final Map<String, String> jmxToJavaNameMapping) {
+ public UnionCompositeAttributeMappingStrategy(final CompositeType compositeType,
+ final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies,
+ final Map<String, String> jmxToJavaNameMapping) {
super(compositeType, innerStrategies, jmxToJavaNameMapping);
}
@Override
- protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName, final String description) {
- if(!description.equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)){
+ protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName,
+ final String description) {
+ if (!description.equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)) {
return Optional.absent();
}
return super.mapInnerAttribute(compositeData, jmxName, description);
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import javax.management.openmbean.OpenType;
-abstract class AbstractAttributeResolvingStrategy<T, O extends OpenType<?>> implements AttributeResolvingStrategy<T, O> {
+public abstract class AbstractAttributeResolvingStrategy<T, O extends OpenType<?>>
+ implements AttributeResolvingStrategy<T, O> {
private O openType;
public AbstractAttributeResolvingStrategy(final O openType) {
}
/**
- * Composite types might change during resolution. Use this setter to update open type
+ * Composite types might change during resolution. Use this setter to update
+ * open type
*/
public void setOpenType(final O openType) {
this.openType = openType;
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<Object, ArrayType<?>> {
+public final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<Object, ArrayType<?>> {
private final AttributeResolvingStrategy<?, ? extends OpenType<?>> innerTypeResolvingStrategy;
try {
innerTypeClass = Class.forName(getOpenType().getElementOpenType().getClassName());
} catch (final ClassNotFoundException e) {
- throw new IllegalStateException("Unable to locate class for "
- + getOpenType().getElementOpenType().getClassName(), e);
+ throw new IllegalStateException(
+ "Unable to locate class for " + getOpenType().getElementOpenType().getClassName(), e);
}
}
parsedArray = Array.newInstance(innerTypeClass, valueList.size());
}
- int i = 0;
+ int index = 0;
for (Object innerValue : valueList) {
- Optional<?> parsedElement = innerTypeResolvingStrategy.parseAttribute(attrName + "_" + i, innerValue);
- if (!parsedElement.isPresent()){
+ Optional<?> parsedElement = innerTypeResolvingStrategy.parseAttribute(attrName + "_" + index, innerValue);
+ if (!parsedElement.isPresent()) {
continue;
}
- Array.set(parsedArray, i, parsedElement.get());
- i++;
+ Array.set(parsedArray, index, parsedElement.get());
+ index++;
}
// Rebuild open type. Underlying composite types might have changed
if (innerTypeResolvingStrategy.getOpenType() instanceof CompositeType) {
try {
- final ArrayType<?> openType =
- new ArrayType<>(getOpenType().getDimension(), innerTypeResolvingStrategy.getOpenType());
+ final ArrayType<?> openType = new ArrayType<>(getOpenType().getDimension(),
+ innerTypeResolvingStrategy.getOpenType());
setOpenType(openType);
} catch (final OpenDataException e) {
throw new IllegalStateException("An error occurred during restoration of array type " + this
private static Class<?> getPrimitiveType(final Class<?> innerTypeClass) {
try {
return (Class<?>) innerTypeClass.getField("TYPE").get(null);
- } catch (final Exception e) {
+ } catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) {
throw new IllegalStateException("Unable to determine primitive type to " + innerTypeClass);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-class CompositeAttributeResolvingStrategy extends
- AbstractAttributeResolvingStrategy<CompositeDataSupport, CompositeType> {
+class CompositeAttributeResolvingStrategy
+ extends AbstractAttributeResolvingStrategy<CompositeDataSupport, CompositeType> {
private final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes;
private final Map<String, String> yangToJavaAttrMapping;
private static final Logger LOG = LoggerFactory.getLogger(CompositeAttributeResolvingStrategy.class);
- CompositeAttributeResolvingStrategy(final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
+ CompositeAttributeResolvingStrategy(
+ final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
final CompositeType openType, final Map<String, String> yangToJavaAttrMapping) {
super(openType);
this.innerTypes = innerTypes;
}
@Override
- public Optional<CompositeDataSupport> parseAttribute(final String attrName, final Object value) throws DocumentedException {
+ public Optional<CompositeDataSupport> parseAttribute(final String attrName, final Object value)
+ throws DocumentedException {
if (value == null) {
return Optional.absent();
final String[] names = new String[getOpenType().keySet().size()];
final String[] descriptions = new String[getOpenType().keySet().size()];
OpenType<?>[] itemTypes = new OpenType[names.length];
- int i = 0;
+ int index = 0;
for (Object innerAttrName : innerTypes.keySet()) {
Preconditions.checkState(innerAttrName instanceof String, "Attribute name must be string");
Optional<?> parsedInnerValue = attributeResolvingStrategy.parseAttribute(innerAttrNameStr, valueToParse);
- if(attributeResolvingStrategy instanceof EnumAttributeResolvingStrategy) {
- // Open type for enum contain the class name necessary for its resolution, however in a DTO
+ if (attributeResolvingStrategy instanceof EnumAttributeResolvingStrategy) {
+ // Open type for enum contain the class name necessary for its resolution,
+ // however in a DTO
// the open type need to be just SimpleType.STRING so that JMX is happy
// After the enum attribute is resolved, change its open type back to STRING
openTypes.put(innerAttrNameStr, SimpleType.STRING);
items.put(yangToJavaAttrMapping.get(innerAttrNameStr),
parsedInnerValue.isPresent() ? parsedInnerValue.get() : null);
- // fill names + item types in order to reconstruct the open type for current attribute
- names[i] = yangToJavaAttrMapping.get(innerAttrNameStr);
- descriptions[i] = getOpenType().getDescription(names[i]);
- itemTypes[i] = openTypes.get(innerAttrNameStr);
- i++;
+ // fill names + item types in order to reconstruct the open type for current
+ // attribute
+ names[index] = yangToJavaAttrMapping.get(innerAttrNameStr);
+ descriptions[index] = getOpenType().getDescription(names[index]);
+ itemTypes[index] = openTypes.get(innerAttrNameStr);
+ index++;
}
CompositeDataSupport parsedValue;
try {
LOG.trace("Attribute {} with open type {}. Reconstructing open type.", attrName, getOpenType());
- setOpenType(new CompositeType(getOpenType().getTypeName(), getOpenType().getDescription(), names, descriptions, itemTypes));
+ setOpenType(new CompositeType(getOpenType().getTypeName(), getOpenType().getDescription(), names,
+ descriptions, itemTypes));
LOG.debug("Attribute {}. Open type reconstructed to {}", attrName, getOpenType(), getOpenType());
parsedValue = new CompositeDataSupport(getOpenType(), items);
} catch (final OpenDataException e) {
return Optional.of(parsedValue);
}
-
protected Map<?, ?> preprocessValueMap(final Map<?, ?> valueMap) {
return valueMap;
}
-
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
if (value == null) {
return Optional.absent();
}
-
Util.checkType(value, Map.class);
Map<?, ?> valueMap = (Map<?, ?>) value;
- Preconditions.checkArgument(valueMap.size() == 1, "Unexpected value size " + value + " should be just 1 foe enum");
+ Preconditions.checkArgument(valueMap.size() == 1,
+ "Unexpected value size " + value + " should be just 1 foe enum");
final Object innerValue = valueMap.values().iterator().next();
Util.checkType(innerValue, String.class);
final String className = getOpenType().getTypeName();
- final Object parsedValue = enumResolver.fromYang(className, ((String) innerValue));
+ final Object parsedValue = enumResolver.fromYang(className, (String) innerValue);
- LOG.debug("Attribute {} : {} parsed to enum type {} with value {}", attrName, innerValue, getOpenType(), parsedValue);
+ LOG.debug("Attribute {} : {} parsed to enum type {} with value {}", attrName, innerValue, getOpenType(),
+ parsedValue);
return Optional.of(parsedValue);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ObjectNameAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<ObjectName, SimpleType<?>> {
+public class ObjectNameAttributeResolvingStrategy
+ extends AbstractAttributeResolvingStrategy<ObjectName, SimpleType<?>> {
private final ServiceRegistryWrapper serviceTracker;
private static final Logger LOG = LoggerFactory.getLogger(ObjectNameAttributeResolvingStrategy.class);
Util.checkType(value, ObjectNameAttributeMappingStrategy.MappedDependency.class);
- ObjectNameAttributeMappingStrategy.MappedDependency mappedDep = (ObjectNameAttributeMappingStrategy.MappedDependency) value;
+ ObjectNameAttributeMappingStrategy.MappedDependency mappedDep =
+ (ObjectNameAttributeMappingStrategy.MappedDependency) value;
String serviceName = mappedDep.getServiceName();
String refName = mappedDep.getRefName();
String namespace = mappedDep.getNamespace();
LOG.debug("Attribute {} : {} parsed to type {}", attrName, value, getOpenType());
return Optional.of(on);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> strategies = Maps.newHashMap();
for (Entry<String, AttributeIfc> attrEntry : configDefinition.entrySet()) {
- strategies.put(attrEntry.getKey(),
- prepareStrategy(attrEntry.getValue()));
+ strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue()));
}
return strategies;
private Map<String, String> createYangToJmxMapping(final TOAttribute attributeIfc) {
Map<String, String> retVal = Maps.newHashMap();
for (Entry<String, AttributeIfc> entry : attributeIfc.getYangPropertiesToTypesMap().entrySet()) {
- retVal.put(entry.getKey(), (entry.getValue()).getLowerCaseCammelCase());
+ retVal.put(entry.getKey(), entry.getValue().getLowerCaseCammelCase());
}
return retVal;
}
}
@Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaSimpleAttribute(final SimpleType<?> openType) {
+ protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaSimpleAttribute(
+ final SimpleType<?> openType) {
return new SimpleAttributeResolvingStrategy(openType);
}
@Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaArrayAttribute(final ArrayType<?> openType) {
+ protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaArrayAttribute(final ArrayType<?> openType) {
SimpleType<?> innerType = (SimpleType<?>) openType.getElementOpenType();
AttributeResolvingStrategy<?, ? extends OpenType<?>> strat = new SimpleAttributeResolvingStrategy(innerType);
}
@Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(final CompositeType openType) {
+ protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(
+ final CompositeType openType) {
Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap = Maps.newHashMap();
Map<String, String> yangToJmxMapping = Maps.newHashMap();
return new CompositeAttributeResolvingStrategy(innerMap, openType, yangToJmxMapping);
}
- private void fillMappingForComposite(final CompositeType openType, final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap, final Map<String, String> yangToJmxMapping) {
+ private void fillMappingForComposite(final CompositeType openType,
+ final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap,
+ final Map<String, String> yangToJmxMapping) {
for (String innerAttributeKey : openType.keySet()) {
innerMap.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey)));
yangToJmxMapping.put(innerAttributeKey, innerAttributeKey);
for (String innerName : openType.keySet()) {
AttributeIfc innerAttributeIfc = toAttribute.getJmxPropertiesToTypesMap().get(innerName);
- innerMap.put(innerAttributeIfc.getAttributeYangName(),
- prepareStrategy(innerAttributeIfc));
+ innerMap.put(innerAttributeIfc.getAttributeYangName(), prepareStrategy(innerAttributeIfc));
}
return new CompositeAttributeResolvingStrategy(innerMap, openType, createYangToJmxMapping(toAttribute));
}
}
@Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(final ArrayType<?> openType) {
+ protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(
+ final ArrayType<?> openType) {
Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
return new ArrayAttributeResolvingStrategy(caseDependencyAttribute(SimpleType.OBJECTNAME), openType);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
Util.checkType(value, String.class);
- Resolver prefferedPlugin = resolverPlugins.get(cls.getCanonicalName());
- prefferedPlugin = prefferedPlugin == null ? resolverPlugins.get(DEFAULT_RESOLVERS) : prefferedPlugin;
+ Resolver prefferedPlugin = RESOLVER_PLUGINS.get(cls.getCanonicalName());
+ prefferedPlugin = prefferedPlugin == null ? RESOLVER_PLUGINS.get(DEFAULT_RESOLVERS) : prefferedPlugin;
Object parsedValue = prefferedPlugin.resolveObject(cls, attrName, (String) value);
LOG.debug("Attribute {} : {} parsed to type {} with value {}", attrName, value, getOpenType(), parsedValue);
}
private static final String DEFAULT_RESOLVERS = "default";
- private static final Map<String, Resolver> resolverPlugins = Maps.newHashMap();
+ private static final Map<String, Resolver> RESOLVER_PLUGINS = Maps.newHashMap();
static {
- resolverPlugins.put(DEFAULT_RESOLVERS, new DefaultResolver());
- resolverPlugins.put(String.class.getCanonicalName(), new StringResolver());
- resolverPlugins.put(Date.class.getCanonicalName(), new DateResolver());
- resolverPlugins.put(Character.class.getCanonicalName(), new CharResolver());
- resolverPlugins.put(BigInteger.class.getCanonicalName(), new BigIntegerResolver());
- resolverPlugins.put(BigDecimal.class.getCanonicalName(), new BigDecimalResolver());
+ RESOLVER_PLUGINS.put(DEFAULT_RESOLVERS, new DefaultResolver());
+ RESOLVER_PLUGINS.put(String.class.getCanonicalName(), new StringResolver());
+ RESOLVER_PLUGINS.put(Date.class.getCanonicalName(), new DateResolver());
+ RESOLVER_PLUGINS.put(Character.class.getCanonicalName(), new CharResolver());
+ RESOLVER_PLUGINS.put(BigInteger.class.getCanonicalName(), new BigIntegerResolver());
+ RESOLVER_PLUGINS.put(BigDecimal.class.getCanonicalName(), new BigDecimalResolver());
}
interface Resolver {
static class DefaultResolver implements Resolver {
@Override
- public Object resolveObject(final Class<?> type, final String attrName, final String value) throws DocumentedException {
+ public Object resolveObject(final Class<?> type, final String attrName, final String value)
+ throws DocumentedException {
try {
return parseObject(type, value);
- } catch (final Exception e) {
+ } catch (final DocumentedException e) {
throw new DocumentedException("Unable to resolve attribute " + attrName + " from " + value,
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
method = type.getMethod("valueOf", String.class);
return method.invoke(null, value);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- LOG.trace("Error parsing object ",e);
- throw new DocumentedException("Error parsing object.",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
+ LOG.trace("Error parsing object ", e);
+ throw new DocumentedException("Error parsing object.", DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
}
}
}
static class CharResolver extends DefaultResolver {
@Override
- protected Object parseObject(final Class<?> type, final String value) {
+ protected Object parseObject(final Class<?> type, final String value) {
return value.charAt(0);
}
}
try {
return Util.readDate(value);
} catch (final ParseException e) {
- LOG.trace("Unable parse value {} due to ",value, e);
- throw new DocumentedException("Unable to parse value "+value+" as date.",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ LOG.trace("Unable parse value {} due to ", value, e);
+ throw new DocumentedException("Unable to parse value " + value + " as date.",
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
final class UnionCompositeAttributeResolvingStrategy extends CompositeAttributeResolvingStrategy {
- UnionCompositeAttributeResolvingStrategy(final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
- final CompositeType openType, final Map<String, String> yangToJavaAttrMapping) {
+ UnionCompositeAttributeResolvingStrategy(
+ final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
+ final CompositeType openType, final Map<String, String> yangToJavaAttrMapping) {
super(innerTypes, openType, yangToJavaAttrMapping);
}
+ @Override
protected Map<String, Object> preprocessValueMap(final Map<?, ?> valueMap) {
CompositeType openType = getOpenType();
Map<String, Object> newMap = Maps.newHashMap();
for (String key : openType.keySet()) {
- if (openType.getDescription(key).equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)){
+ if (openType.getDescription(key).equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)) {
newMap.put(key, valueMap.get(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION));
} else {
newMap.put(key, null);
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private final Document document;
private final String key;
- /**
- * @param document
- * @param key
- */
public ObjectNameAttributeWritingStrategy(final Document document, final String key) {
this.document = document;
this.key = key;
String refName = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getRefName();
String namespaceForType = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getNamespace();
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY, XmlMappingConstants.PREFIX,
- namespaceForType, moduleName);
+ Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
+ XmlMappingConstants.PREFIX, namespaceForType, moduleName);
innerNode.appendChild(typeElement);
- final Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, refName, Optional.<String>absent());
+ final Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, refName,
+ Optional.<String>absent());
innerNode.appendChild(nameElement);
parentElement.appendChild(innerNode);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
return preparedWriting;
}
- public AttributeWritingStrategy prepareWritingStrategy(final String key, final AttributeIfc expectedAttr, final Document document) {
+ public AttributeWritingStrategy prepareWritingStrategy(final String key, final AttributeIfc expectedAttr,
+ final Document document) {
Preconditions.checkNotNull(expectedAttr, "Mbean attributes mismatch, unable to find expected attribute for %s",
key);
this.document = document;
Map<String, AttributeWritingStrategy> innerStrats = Maps.newHashMap();
String currentKey = key;
- for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute()).getYangPropertiesToTypesMap().entrySet()) {
+ for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute())
+ .getYangPropertiesToTypesMap().entrySet()) {
AttributeWritingStrategy innerStrategy = prepareWritingStrategy(innerAttrEntry.getKey(),
innerAttrEntry.getValue(), document);
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private final Document document;
private final String key;
- /**
- * @param document
- * @param key
- */
public SimpleAttributeWritingStrategy(final Document document, final String key) {
this.document = document;
this.key = key;
parentElement.appendChild(innerNode);
}
- protected Element createElement(final Document document, final String key, final String value, final Optional<String> namespace) {
+ protected Element createElement(final Document document, final String key, final String value,
+ final Optional<String> namespace) {
Element typeElement = XmlUtil.createElement(document, key, namespace);
typeElement.appendChild(document.createTextNode(value));
return typeElement;
}
+
protected Object preprocess(final Object value) {
return value;
}
-
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class SimpleBinaryAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
- /**
- * @param document
- * @param key
- */
public SimpleBinaryAttributeWritingStrategy(final Document document, final String key) {
super(document, key);
}
List<?> list = (List<?>) value;
byte[] decoded = new byte[list.size()];
- int i = 0;
- for (Object bAsStr : list) {
- Preconditions.checkArgument(bAsStr instanceof String, "Unexpected inner value for %s, expected string", value);
- byte b = Byte.parseByte((String) bAsStr);
- decoded[i++] = b;
+ int index = 0;
+ for (Object basStr : list) {
+ Preconditions.checkArgument(basStr instanceof String, "Unexpected inner value for %s, expected string",
+ value);
+ decoded[index++] = Byte.parseByte((String) basStr);
}
-
return en.encode(decoded);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class SimpleCompositeAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
- /**
- * @param document
- * @param key
- */
public SimpleCompositeAttributeWritingStrategy(final Document document, final String key) {
super(document, key);
}
+ @Override
protected Object preprocess(final Object value) {
Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>)value).size() == 1, "Unexpected number of values in %s, expected 1", value);
- return ((Map<?, ?>)value).values().iterator().next();
+ Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
+ value);
+ return ((Map<?, ?>) value).values().iterator().next();
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private static final String PREFIX = "prefix";
- /**
- * @param document
- * @param key
- */
public SimpleIdentityRefAttributeWritingStrategy(final Document document, final String key) {
super(document, key);
}
+ @Override
protected Object preprocess(final Object value) {
Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>)value).size() == 1, "Unexpected number of values in %s, expected 1", value);
+ Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
+ value);
Object stringValue = ((Map<?, ?>) value).values().iterator().next();
Util.checkType(stringValue, String.class);
}
@Override
- protected Element createElement(final Document doc, final String key, final String value, final Optional<String> namespace) {
- QName qName = QName.create(value);
- String identityValue = qName.getLocalName();
- String identityNamespace = qName.getNamespace().toString();
- return XmlUtil.createTextElementWithNamespacedContent(doc, key, PREFIX, identityNamespace, identityValue, namespace);
+ protected Element createElement(final Document doc, final String key, final String value,
+ final Optional<String> namespace) {
+ QName qualifiedName = QName.create(value);
+ String identityValue = qualifiedName.getLocalName();
+ String identityNamespace = qualifiedName.getNamespace().toString();
+ return XmlUtil.createTextElementWithNamespacedContent(doc, key, PREFIX, identityNamespace, identityValue,
+ namespace);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
- /**
- * @param document
- * @param key
- */
public SimpleUnionAttributeWritingStrategy(final Document document, final String key) {
super(document, key);
}
+ @Override
protected Object preprocess(final Object value) {
Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>)value).size() == 1, "Unexpected number of values in %s, expected 1", value);
+ Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
+ value);
Object listOfStrings = ((Map<?, ?>) value).values().iterator().next();
Util.checkType(listOfStrings, List.class);
- StringBuilder b = new StringBuilder();
- for (Object character: (List<?>)listOfStrings) {
+ StringBuilder builder = new StringBuilder();
+ for (Object character : (List<?>) listOfStrings) {
Util.checkType(character, String.class);
- b.append(character);
+ builder.append(character);
}
-
- return b.toString();
+ return builder.toString();
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
package org.opendaylight.controller.config.facade.xml.mapping.config;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-
public class Config {
private final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleConfig>> moduleConfigs;
+ Map<String /* Name of module entry from yang file */,
+ ModuleConfig>> moduleConfigs;
private final Map<String, Map<Date, IdentityMapping>> identityMap;
this(moduleConfigs, Collections.<String, Map<Date, IdentityMapping>>emptyMap(), enumResolver);
}
- public Config(final Map<String, Map<String, ModuleConfig>> moduleConfigs, final Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) {
+ public Config(final Map<String, Map<String, ModuleConfig>> moduleConfigs,
+ final Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) {
this.moduleConfigs = moduleConfigs;
this.identityMap = identityMap;
this.enumResolver = enumResolver;
}
- public static Map<String, Map<String, Collection<ObjectName>>> getMappedInstances(final Set<ObjectName> instancesToMap,
- final Map<String, Map<String, ModuleConfig>> configs) {
+ public static Map<String, Map<String, Collection<ObjectName>>> getMappedInstances(
+ final Set<ObjectName> instancesToMap, final Map<String, Map<String, ModuleConfig>> configs) {
Multimap<String, ObjectName> moduleToInstances = mapInstancesToModules(instancesToMap);
Map<String, Map<String, Collection<ObjectName>>> retVal = Maps.newLinkedHashMap();
// TODO, this code does not support same module names from different namespaces
// Namespace should be present in ObjectName
- if (instances == null){
+ if (instances == null) {
continue;
}
innerRetVal.put(moduleName, instances);
}
-
retVal.put(namespaceToModuleToConfigEntry.getKey(), innerRetVal);
}
return retVal;
return retVal;
}
- public Element toXml(final Set<ObjectName> instancesToMap, final Optional<String> maybeNamespace, final Document document,
- final Element dataElement, final ServiceRegistryWrapper serviceTracker) {
+ public Element toXml(final Set<ObjectName> instancesToMap, final Optional<String> maybeNamespace,
+ final Document document, final Element dataElement, final ServiceRegistryWrapper serviceTracker) {
Map<String, Map<String, Collection<ObjectName>>> moduleToInstances = getMappedInstances(instancesToMap,
moduleConfigs);
dataElement.setAttributeNS(maybeNamespace.get(), dataElement.getNodeName(), "xmlns");
}
- Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
+ Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
+ Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
dataElement.appendChild(modulesElement);
for (Entry<String, Map<String, Collection<ObjectName>>> moduleToInstanceEntry : moduleToInstances.entrySet()) {
for (Entry<String, Collection<ObjectName>> moduleMappingEntry : moduleToInstanceEntry.getValue()
.entrySet()) {
- ModuleConfig mapping = moduleConfigs.get(moduleToInstanceEntry.getKey()).get(moduleMappingEntry.getKey());
+ ModuleConfig mapping = moduleConfigs.get(moduleToInstanceEntry.getKey())
+ .get(moduleMappingEntry.getKey());
if (moduleMappingEntry.getValue().isEmpty()) {
continue;
}
for (ObjectName objectName : moduleMappingEntry.getValue()) {
- modulesElement.appendChild(mapping.toXml(objectName, document, moduleToInstanceEntry.getKey(), enumResolver));
+ modulesElement.appendChild(
+ mapping.toXml(objectName, document, moduleToInstanceEntry.getKey(), enumResolver));
}
}
}
public Element moduleToXml(final String moduleNamespace, final String factoryName, final String instanceName,
- final ObjectName instanceON, final Document document) {
+ final ObjectName instanceON, final Document document) {
ModuleConfig moduleConfig = getModuleMapping(moduleNamespace, instanceName, factoryName);
return moduleConfig.toXml(instanceON, document, moduleNamespace, enumResolver);
}
// TODO refactor, replace Map->Multimap with e.g. ConfigElementResolved
// class
- public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(final XmlElement xml, final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker) throws DocumentedException {
+ public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(final XmlElement xml,
+ final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker)
+ throws DocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
Map<String, Multimap<String, ModuleElementResolved>> retVal = Maps.newHashMap();
for (XmlElement moduleElement : moduleElements) {
- ResolvingStrategy<ModuleElementResolved> resolvingStrategy = new ResolvingStrategy<ModuleElementResolved>() {
- @Override
- public ModuleElementResolved resolveElement(final ModuleConfig moduleMapping, final XmlElement moduleElement, final ServiceRegistryWrapper serviceTracker, final String instanceName, final String moduleNamespace, final EditStrategyType defaultStrategy) throws DocumentedException {
- return moduleMapping.fromXml(moduleElement, serviceTracker,
- instanceName, moduleNamespace, defaultStrategy, identityMap, enumResolver);
- }
- };
+ ResolvingStrategy<ModuleElementResolved> resolvingStrategy = (moduleMapping, moduleElement1,
+ serviceTracker1, instanceName, moduleNamespace,
+ defaultStrategy) -> moduleMapping.fromXml(moduleElement1, serviceTracker1, instanceName,
+ moduleNamespace, defaultStrategy, identityMap, enumResolver);
resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
}
}
/**
- * return a map containing namespace -> moduleName -> instanceName map. Attribute parsing is omitted.
+ * return a map containing namespace -> moduleName -> instanceName map.
+ * Attribute parsing is omitted.
*/
public Map<String, Multimap<String, ModuleElementDefinition>> fromXmlModulesMap(final XmlElement xml,
- final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker) throws DocumentedException {
+ final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker)
+ throws DocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
Map<String, Multimap<String, ModuleElementDefinition>> retVal = Maps.newHashMap();
for (XmlElement moduleElement : moduleElements) {
- ResolvingStrategy<ModuleElementDefinition> resolvingStrategy = new ResolvingStrategy<ModuleElementDefinition>() {
- @Override
- public ModuleElementDefinition resolveElement(final ModuleConfig moduleMapping, final XmlElement moduleElement,
- final ServiceRegistryWrapper serviceTracker, final String instanceName, final String moduleNamespace,
- final EditStrategyType defaultStrategy) {
- // TODO: add check for conflicts between global and local
- // edit strategy
- String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- return new ModuleElementDefinition(instanceName, perInstanceEditStrategy, defaultStrategy);
- }
+ ResolvingStrategy<ModuleElementDefinition> resolvingStrategy = (moduleMapping, moduleElement1,
+ serviceTracker1, instanceName, moduleNamespace, defaultStrategy) -> {
+ // TODO: add check for conflicts between global and local
+ // edit strategy
+ String perInstanceEditStrategy = moduleElement1.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ return new ModuleElementDefinition(instanceName, perInstanceEditStrategy, defaultStrategy);
};
resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
private static Optional<XmlElement> getModulesElement(final XmlElement xml) {
return xml.getOnlyChildElementOptionally(XmlMappingConstants.MODULES_KEY,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
- private List<XmlElement> getModulesElementList(final Optional<XmlElement> modulesElement) throws DocumentedException {
+ private List<XmlElement> getModulesElementList(final Optional<XmlElement> modulesElement)
+ throws DocumentedException {
List<XmlElement> moduleElements;
if (modulesElement.isPresent()) {
return moduleElements;
}
- private <T> void resolveModule(final Map<String, Multimap<String, T>> retVal, final ServiceRegistryWrapper serviceTracker,
- final XmlElement moduleElement, final EditStrategyType defaultStrategy, final ResolvingStrategy<T> resolvingStrategy) throws DocumentedException {
+ private <T> void resolveModule(final Map<String, Multimap<String, T>> retVal,
+ final ServiceRegistryWrapper serviceTracker, final XmlElement moduleElement,
+ final EditStrategyType defaultStrategy, final ResolvingStrategy<T> resolvingStrategy)
+ throws DocumentedException {
XmlElement typeElement = null;
typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
Entry<String, String> prefixToNamespace = typeElement.findNamespaceOfTextContent();
Multimap<String, T> innerMap = retVal.computeIfAbsent(moduleNamespace, k -> HashMultimap.create());
- T resolvedElement = resolvingStrategy.resolveElement(moduleMapping, moduleElement, serviceTracker,
- instanceName, moduleNamespace, defaultStrategy);
+ T resolvedElement = resolvingStrategy.resolveElement(moduleMapping, moduleElement, serviceTracker, instanceName,
+ moduleNamespace, defaultStrategy);
innerMap.put(factoryName, resolvedElement);
}
private static Optional<XmlElement> getServicesElement(final XmlElement xml) {
return xml.getOnlyChildElementOptionally(XmlMappingConstants.SERVICES_KEY,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
public static void checkUnrecognisedChildren(final XmlElement parent) throws DocumentedException {
Optional<XmlElement> modulesOpt = getModulesElement(parent);
List<XmlElement> recognised = Lists.newArrayList();
- if(servicesOpt.isPresent()){
+ if (servicesOpt.isPresent()) {
recognised.add(servicesOpt.get());
}
- if(modulesOpt.isPresent()){
+ if (modulesOpt.isPresent()) {
recognised.add(modulesOpt.get());
}
}
private String getFactoryName(final String factoryNameWithPrefix, final String prefixOrEmptyString) {
- checkState(
- factoryNameWithPrefix.startsWith(prefixOrEmptyString),
+ checkState(factoryNameWithPrefix.startsWith(prefixOrEmptyString),
String.format("Internal error: text " + "content '%s' of type node does not start with prefix '%s'",
factoryNameWithPrefix, prefixOrEmptyString));
return factoryNameWithPrefix.substring(factoryNameAfterPrefixIndex);
}
- private ModuleConfig getModuleMapping(final String moduleNamespace, final String instanceName, final String factoryName) {
+ private ModuleConfig getModuleMapping(final String moduleNamespace, final String instanceName,
+ final String factoryName) {
Map<String, ModuleConfig> mappingsFromNamespace = moduleConfigs.get(moduleNamespace);
Preconditions.checkNotNull(mappingsFromNamespace,
private interface ResolvingStrategy<T> {
T resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker,
- String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws DocumentedException;
+ String instanceName, String moduleNamespace, EditStrategyType defaultStrategy)
+ throws DocumentedException;
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+
import javax.management.ObjectName;
import javax.management.openmbean.OpenType;
+
import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeReadingStrategy;
this.configRegistryClient = configRegistryClient;
}
+ @SuppressWarnings("IllegalCatch")
private Map<String, Object> getMappedConfiguration(final ObjectName on, final EnumResolver enumResolver) {
// TODO make field, mappingStrategies can be instantiated only once
for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
// Skip children runtime beans as they are mapped by InstanceRuntime
- if (configDefEntry.getValue() instanceof RuntimeBeanEntry){
+ if (configDefEntry.getValue() instanceof RuntimeBeanEntry) {
continue;
}
Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
try {
AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
.get(configDefEntry.getKey());
- Optional<?> a = attributeMappingStrategy.mapAttribute(value);
- if (!a.isPresent()){
+ Optional<?> attribute = attributeMappingStrategy.mapAttribute(value);
+ if (!attribute.isPresent()) {
continue;
}
- toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
- } catch (final Exception e) {
+ toXml.put(configDefEntry.getValue().getAttributeYangName(), attribute.get());
+ } catch (final RuntimeException e) {
throw new IllegalStateException("Unable to map value " + value + " to attribute "
+ configDefEntry.getKey(), e);
}
return toXml;
}
- public Element toXml(final ObjectName on, final String namespace, final Document document, final Element rootElement, final EnumResolver enumResolver) {
+ @SuppressWarnings("IllegalCatch")
+ public Element toXml(final ObjectName on, final String namespace, final Document document,
+ final Element rootElement, final EnumResolver enumResolver) {
Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
Map<String, Object> mappedConfig = getMappedConfiguration(on, enumResolver);
Element parentElement;
for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
try {
strats.get(mappingEntry.getKey()).writeElement(parentElement, namespace, mappingEntry.getValue());
- } catch (final Exception e) {
+ } catch (final RuntimeException e) {
throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
+ mappingEntry.getValue(), e);
}
return rootElement;
}
- private void resolveConfiguration(final InstanceConfigElementResolved mappedConfig, final ServiceRegistryWrapper depTracker, final EnumResolver enumResolver) {
+ private void resolveConfiguration(final InstanceConfigElementResolved mappedConfig,
+ final ServiceRegistryWrapper depTracker, final EnumResolver enumResolver) {
// TODO make field, resolvingStrategies can be instantiated only once
Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
try {
AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
.get(attributeName);
- LOG.trace("Trying to set value {} of attribute {} with {}", value, attributeName, attributeResolvingStrategy);
+ LOG.trace("Trying to set value {} of attribute {} with {}", value, attributeName,
+ attributeResolvingStrategy);
value.resolveValue(attributeResolvingStrategy, attributeName);
- value.setJmxName(
- yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
- } catch (final Exception e) {
- throw new IllegalStateException("Unable to resolve value " + value
- + " to attribute " + attributeName, e);
+ value.setJmxName(yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
+ } catch (final DocumentedException e) {
+ throw new IllegalStateException("Unable to resolve value " + value + " to attribute " + attributeName,
+ e);
}
}
}
- public InstanceConfigElementResolved fromXml(XmlElement moduleElement, final ServiceRegistryWrapper services, final String moduleNamespace,
- final EditStrategyType defaultStrategy,
- final Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) throws DocumentedException {
+ public InstanceConfigElementResolved fromXml(XmlElement moduleElement, final ServiceRegistryWrapper services,
+ final String moduleNamespace, final EditStrategyType defaultStrategy,
+ final Map<String, Map<Date, IdentityMapping>> identityMap,
+ final EnumResolver enumResolver)
+ throws DocumentedException {
Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
- Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
+ Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig,
+ identityMap);
List<XmlElement> recognisedChildren = Lists.newArrayList();
XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
int size = moduleElement.getChildElements().size();
int expectedChildNodes = 1 + typeAndNameElements.size();
if (size > expectedChildNodes) {
- throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
- nameElement.getTextContent() + " - Expected " + expectedChildNodes +" child nodes, " +
- "one of them with name " + nullableDummyContainerName +
- ", got " + size + " elements.");
+ throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : "
+ + nameElement.getTextContent() + " - Expected " + expectedChildNodes + " child nodes, "
+ + "one of them with name " + nullableDummyContainerName + ", got " + size + " elements.");
}
if (size == expectedChildNodes) {
try {
moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
} catch (final DocumentedException e) {
- throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
- nameElement.getTextContent() + " - Expected child node with name " + nullableDummyContainerName +
- "." + e.getMessage());
+ throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : "
+ + nameElement.getTextContent() + " - Expected child node with name "
+ + nullableDummyContainerName + "." + e.getMessage());
}
} // else 2 elements, no need to descend
}
try {
moduleElement.checkUnrecognisedElements(recognisedChildren);
} catch (final DocumentedException e) {
- throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
- nameElement.getTextContent() + " - " +
- e.getMessage(), e.getErrorType(), e.getErrorTag(),e.getErrorSeverity(),e.getErrorInfo());
+ throw new DocumentedException(
+ "Error reading module " + typeElement.getTextContent() + " : " + nameElement.getTextContent()
+ + " - " + e.getMessage(),
+ e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
// TODO: add check for conflicts between global and local edit strategy
String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
- retVal, defaultStrategy) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
+ InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("")
+ ? new InstanceConfigElementResolved(retVal, defaultStrategy)
+ : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
resolveConfiguration(instanceConfigElementResolved, services, enumResolver);
return instanceConfigElementResolved;
}
- private List<XmlElement> getConfigNodes(final XmlElement moduleElement, final String moduleNamespace, final String name,
- final List<XmlElement> recognisedChildren, final List<XmlElement> typeAndName) throws DocumentedException {
+ private List<XmlElement> getConfigNodes(final XmlElement moduleElement, final String moduleNamespace,
+ final String name, final List<XmlElement> recognisedChildren,
+ final List<XmlElement> typeAndName)
+ throws DocumentedException {
List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
if (foundConfigNodes.isEmpty()) {
LOG.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
foundWithoutNamespaceNodes.removeAll(typeAndName);
- if (!foundWithoutNamespaceNodes.isEmpty()){
- throw new DocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
- foundWithoutNamespaceNodes),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
+ if (!foundWithoutNamespaceNodes.isEmpty()) {
+ throw new DocumentedException(
+ String.format("Element %s present multiple times with different namespaces: %s, %s", name,
+ foundConfigNodes, foundWithoutNamespaceNodes),
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.INVALID_VALUE,
DocumentedException.ErrorSeverity.ERROR);
}
}
-
recognisedChildren.addAll(foundConfigNodes);
return foundConfigNodes;
}
for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
}
-
return reversednameToAtr;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private final EditStrategyType editStrategy;
private final Map<String, AttributeConfigElement> configuration;
- public InstanceConfigElementResolved(final String currentStrategy, final Map<String, AttributeConfigElement> configuration,
- final EditStrategyType defaultStrategy)
+ public InstanceConfigElementResolved(final String currentStrategy,
+ final Map<String, AttributeConfigElement> configuration, final EditStrategyType defaultStrategy)
throws DocumentedException {
this.editStrategy = parseStrategy(currentStrategy, defaultStrategy);
this.configuration = configuration;
}
- public InstanceConfigElementResolved(final Map<String, AttributeConfigElement> configuration, final EditStrategyType defaultStrategy) {
+ public InstanceConfigElementResolved(final Map<String, AttributeConfigElement> configuration,
+ final EditStrategyType defaultStrategy) {
editStrategy = defaultStrategy;
this.configuration = configuration;
}
-
- static EditStrategyType parseStrategy(final String currentStrategy, final EditStrategyType defaultStrategy) throws OperationNotPermittedException {
+ static EditStrategyType parseStrategy(final String currentStrategy, final EditStrategyType defaultStrategy)
+ throws OperationNotPermittedException {
EditStrategyType parsedStrategy = EditStrategyType.valueOf(currentStrategy);
- EditStrategyType.compareParsedStrategyToDefaultEnforcing(parsedStrategy,defaultStrategy);
+ EditStrategyType.compareParsedStrategyToDefaultEnforcing(parsedStrategy, defaultStrategy);
return parsedStrategy;
}
-
public EditConfigStrategy getEditStrategy() {
return editStrategy.getFittingStrategy();
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
this.instanceConfig = mbeanMapping;
}
- public Element toXml(final ObjectName instanceON, final Document document, final String namespace, final EnumResolver enumResolver) {
- final Optional<String> configNs =
- Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ public Element toXml(final ObjectName instanceON, final Document document, final String namespace,
+ final EnumResolver enumResolver) {
+ final Optional<String> configNs = Optional
+ .of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
Element root = XmlUtil.createElement(document, XmlMappingConstants.MODULE_KEY, configNs);
- // type belongs to config.yang namespace, but needs to be <type prefix:moduleNS>prefix:moduleName</type>
+ // type belongs to config.yang namespace, but needs to be <type
+ // prefix:moduleNS>prefix:moduleName</type>
Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
XmlMappingConstants.PREFIX, namespace, moduleName, configNs);
return root;
}
- public ModuleElementResolved fromXml(final XmlElement moduleElement, final ServiceRegistryWrapper depTracker, final String instanceName,
- final String moduleNamespace, final EditStrategyType defaultStrategy, final Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) throws DocumentedException {
+ public ModuleElementResolved fromXml(final XmlElement moduleElement, final ServiceRegistryWrapper depTracker,
+ final String instanceName, final String moduleNamespace, final EditStrategyType defaultStrategy,
+ final Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver)
+ throws DocumentedException {
- InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace, defaultStrategy, identityMap, enumResolver);
+ InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace,
+ defaultStrategy, identityMap, enumResolver);
return new ModuleElementResolved(instanceName, ice);
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public class ModuleElementDefinition {
public static final NoneEditConfigStrategy NONE_EDIT_CONFIG_STRATEGY = new NoneEditConfigStrategy();
- public static final MissingInstanceHandlingStrategy MISSING_INSTANCE_HANDLING_STRATEGY = new MissingInstanceHandlingStrategy();
+ public static final MissingInstanceHandlingStrategy MISSING_INSTANCE_HANDLING_STRATEGY =
+ new MissingInstanceHandlingStrategy();
private final String instanceName;
private final EditStrategyType editStrategy;
private static final Logger LOG = LoggerFactory.getLogger(ModuleElementDefinition.class);
- public ModuleElementDefinition(final String instanceName, final String currentStrategy, final EditStrategyType defaultStrategy) {
+ public ModuleElementDefinition(final String instanceName, final String currentStrategy,
+ final EditStrategyType defaultStrategy) {
this.instanceName = instanceName;
if (currentStrategy == null || currentStrategy.isEmpty()) {
this.editStrategy = defaultStrategy;
} else {
- EditStrategyType _edStrategy = null;
+ EditStrategyType edStrategy = null;
try {
- _edStrategy = InstanceConfigElementResolved.parseStrategy(currentStrategy, defaultStrategy);
+ edStrategy = InstanceConfigElementResolved.parseStrategy(currentStrategy, defaultStrategy);
} catch (final OperationNotPermittedException e) {
- _edStrategy = defaultStrategy;
- LOG.warn("Operation not permitted on current strategy {} while default strategy is {}. Element definition strategy set to default.",
- currentStrategy,
- defaultStrategy,
- e);
+ edStrategy = defaultStrategy;
+ LOG.warn(
+ "Operation not permitted on current strategy {} while default strategy "
+ + "is {}. Element definition strategy set to default.",
+ currentStrategy, defaultStrategy, e);
}
- this.editStrategy = _edStrategy;
+ this.editStrategy = edStrategy;
}
}
public EditConfigStrategy getEditStrategy() {
switch (editStrategy) {
- case delete :
- case remove :
- case none :
- return NONE_EDIT_CONFIG_STRATEGY;
- default :
- return MISSING_INSTANCE_HANDLING_STRATEGY;
+ case delete:
+ case remove:
+ case none:
+ return NONE_EDIT_CONFIG_STRATEGY;
+ default:
+ return MISSING_INSTANCE_HANDLING_STRATEGY;
}
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private final String instanceName;
private final InstanceConfigElementResolved instanceConfigElementResolved;
- public ModuleElementResolved(final String instanceName, final InstanceConfigElementResolved instanceConfigElementResolved) {
+ public ModuleElementResolved(final String instanceName,
+ final InstanceConfigElementResolved instanceConfigElementResolved) {
this.instanceName = instanceName;
this.instanceConfigElementResolved = instanceConfigElementResolved;
}
public InstanceConfigElementResolved getInstanceConfigElementResolved() {
return instanceConfigElementResolved;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
Map<String, Map<String, String>> serviceNameToRefNameToInstance = mappedServices.get(namespace);
Preconditions.checkArgument(serviceNameToRefNameToInstance != null,
- "No service mapped to %s:%s:%s. Wrong namespace, available namespaces: %s",
- namespace, serviceType, refName, mappedServices.keySet());
+ "No service mapped to %s:%s:%s. Wrong namespace, available namespaces: %s", namespace, serviceType,
+ refName, mappedServices.keySet());
Map<String, String> refNameToInstance = serviceNameToRefNameToInstance.get(serviceType);
Preconditions.checkArgument(refNameToInstance != null,
- "No service mapped to %s:%s:%s. Wrong service type, available service types: %s"
- , namespace, serviceType, refName, serviceNameToRefNameToInstance.keySet());
+ "No service mapped to %s:%s:%s. Wrong service type, available service types: %s", namespace,
+ serviceType, refName, serviceNameToRefNameToInstance.keySet());
String instanceId = refNameToInstance.get(refName);
Preconditions.checkArgument(instanceId != null,
- "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s"
- ,namespace, serviceType, refName, refNameToInstance.keySet());
+ "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
+ refName, refNameToInstance.keySet());
Services.ServiceInstance serviceInstance = Services.ServiceInstance.fromString(instanceId);
Preconditions.checkArgument(serviceInstance != null,
- "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s"
- ,namespace, serviceType, refName, refNameToInstance.keySet());
+ "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
+ refName, refNameToInstance.keySet());
- String qNameOfService = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceType);
+ String serviceName = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceType);
try {
/*
- Remove transaction name as this is redundant - will be stripped in DynamicWritableWrapper,
- and makes it hard to compare with service references got from MXBean attributes
- */
- return ObjectNameUtil.withoutTransactionName(
- configServiceRefRegistry.getServiceReference(qNameOfService, refName));
+ * Remove transaction name as this is redundant - will be stripped in
+ * DynamicWritableWrapper, and makes it hard to compare with service references
+ * got from MXBean attributes
+ */
+ return ObjectNameUtil
+ .withoutTransactionName(configServiceRefRegistry.getServiceReference(serviceName, refName));
} catch (final InstanceNotFoundException e) {
- throw new IllegalArgumentException("No serviceInstance mapped to " + refName
- + " under service name " + serviceType + " , " + refNameToInstance.keySet(), e);
+ throw new IllegalArgumentException("No serviceInstance mapped to " + refName + " under service name "
+ + serviceType + " , " + refNameToInstance.keySet(), e);
}
}
Map<String, Map<String, Map<String, String>>> retVal = new HashMap<>();
Map<String, Map<String, ObjectName>> serviceMapping = configServiceRefRegistry.getServiceMapping();
- for (Map.Entry<String, Map<String, ObjectName>> qNameToRefNameEntry : serviceMapping.entrySet()){
- for (String refName : qNameToRefNameEntry.getValue().keySet()) {
+ for (Map.Entry<String, Map<String, ObjectName>> nameToRefEntry : serviceMapping.entrySet()) {
+ for (String refName : nameToRefEntry.getValue().keySet()) {
- ObjectName on = qNameToRefNameEntry.getValue().get(refName);
+ ObjectName on = nameToRefEntry.getValue().get(refName);
Services.ServiceInstance si = Services.ServiceInstance.fromObjectName(on);
- QName qname = QName.create(qNameToRefNameEntry.getKey());
+ QName qname = QName.create(nameToRefEntry.getKey());
String namespace = qname.getNamespace().toString();
- Map<String, Map<String, String>> serviceToRefs =
- retVal.computeIfAbsent(namespace, k -> new HashMap<>());
+ Map<String, Map<String, String>> serviceToRefs = retVal.computeIfAbsent(namespace,
+ k -> new HashMap<>());
String localName = qname.getLocalName();
Map<String, String> refsToSis = serviceToRefs.computeIfAbsent(localName, k -> new HashMap<>());
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
package org.opendaylight.controller.config.facade.xml.mapping.config;
-
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.HashMap;
public static final String TYPE_KEY = "type";
public static final String SERVICE_KEY = "service";
- private final Map<String /*Namespace*/, Map<String/* ServiceName */, Map<String/* refName */, ServiceInstance>>>
- namespaceToServiceNameToRefNameToInstance = new HashMap<>();
+ private final Map<String
+ /* Namespace */,
+ Map<String/* ServiceName */,
+ Map<String/* refName */,
+ ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = new HashMap<>();
- /**
- *
- */
public Map<String, Map<String, Map<String, ServiceInstance>>> getNamespaceToServiceNameToRefNameToInstance() {
return namespaceToServiceNameToRefNameToInstance;
}
for (Entry<String, String> refEntry : serviceEntry.getValue().entrySet()) {
Map<String, Map<String, ServiceInstance>> namespaceToServices =
- tracker.namespaceToServiceNameToRefNameToInstance.computeIfAbsent(namespace,
- k -> new HashMap<>());
+ tracker.namespaceToServiceNameToRefNameToInstance
+ .computeIfAbsent(namespace, k -> new HashMap<>());
- Map<String, ServiceInstance> refNameToInstance = namespaceToServices
- .computeIfAbsent(serviceName, k -> new HashMap<>());
+ Map<String, ServiceInstance> refNameToInstance = namespaceToServices.computeIfAbsent(serviceName,
+ k -> new HashMap<>());
String refName = refEntry.getKey();
- //we want to compare reference not value of the provider
+ // we want to compare reference not value of the provider
refNameToInstance.put(refName, refEntry.getValue() == EMPTY_PROVIDER
- //provider name cannot be EMPTY_PROVIDER instance unless we are executing delete
+ // provider name cannot be EMPTY_PROVIDER instance unless we are executing
+ // delete
? ServiceInstance.EMPTY_SERVICE_INSTANCE
: ServiceInstance.fromString(refEntry.getValue()));
XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY);
Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
- Preconditions.checkState(prefixNamespace.getKey()!=null && !prefixNamespace.getKey().equals(""), "Type attribute was not prefixed");
+ Preconditions.checkState(prefixNamespace.getKey() != null && !prefixNamespace.getKey().equals(""),
+ "Type attribute was not prefixed");
- Map<String, Map<String, String>> namespaceToServices =
- retVal.computeIfAbsent(prefixNamespace.getValue(), k -> new HashMap<>());
+ Map<String, Map<String, String>> namespaceToServices = retVal.computeIfAbsent(prefixNamespace.getValue(),
+ k -> new HashMap<>());
- String serviceName = ObjectNameAttributeReadingStrategy
- .checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
+ String serviceName = ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement,
+ prefixNamespace);
Map<String, String> innerMap = namespaceToServices.computeIfAbsent(serviceName, k -> new HashMap<>());
XmlElement nameElement = instance.getOnlyChildElement(NAME_KEY);
String refName = nameElement.getTextContent();
- if (!ModifyAction.DELETE.toString().toLowerCase().equals(
- instance.getAttribute(
- XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)))
- {
+ if (!ModifyAction.DELETE.toString().toLowerCase()
+ .equals(instance.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0))) {
XmlElement providerElement = instance.getOnlyChildElement(PROVIDER_KEY);
String providerName = providerElement.getTextContent();
innerMap.put(refName, providerName);
} else {
- //since this is a delete we dont have a provider name - we want empty service instance
+ // since this is a delete we dont have a provider name - we want empty service
+ // instance
innerMap.put(refName, EMPTY_PROVIDER);
}
}
}
public static Element toXml(final ServiceRegistryWrapper serviceRegistryWrapper, final Document document) {
- final Optional<String> configNs = Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ final Optional<String> configNs = Optional
+ .of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
Element root = XmlUtil.createElement(document, XmlMappingConstants.SERVICES_KEY, configNs);
Map<String, Map<String, Map<String, String>>> mappedServices = serviceRegistryWrapper.getMappedServices();
// type belongs to config.yang namespace
String serviceType = serviceEntry.getKey();
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(
- document, XmlMappingConstants.TYPE_KEY, XmlMappingConstants.PREFIX,
- namespaceToRefEntry.getKey(), serviceType, configNs);
+ Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document,
+ XmlMappingConstants.TYPE_KEY, XmlMappingConstants.PREFIX, namespaceToRefEntry.getKey(),
+ serviceType, configNs);
serviceElement.appendChild(typeElement);
for (Entry<String, String> instanceEntry : serviceEntry.getValue().entrySet()) {
- Element instanceElement = XmlUtil.createElement(
- document, XmlMappingConstants.INSTANCE_KEY, configNs);
+ Element instanceElement = XmlUtil.createElement(document, XmlMappingConstants.INSTANCE_KEY,
+ configNs);
serviceElement.appendChild(instanceElement);
- Element nameElement = XmlUtil.createTextElement(
- document, NAME_KEY, instanceEntry.getKey(), configNs);
+ Element nameElement = XmlUtil.createTextElement(document, NAME_KEY, instanceEntry.getKey(),
+ configNs);
instanceElement.appendChild(nameElement);
- Element providerElement = XmlUtil.createTextElement(
- document, PROVIDER_KEY, instanceEntry.getValue(), configNs);
+ Element providerElement = XmlUtil.createTextElement(document, PROVIDER_KEY,
+ instanceEntry.getValue(), configNs);
instanceElement.appendChild(providerElement);
}
}
public static ServiceInstance fromString(String instanceId) {
instanceId = instanceId.trim();
- Matcher matcher = p.matcher(instanceId);
- if(!matcher.matches()) {
- matcher = pDeprecated.matcher(instanceId);
+ Matcher matcher = PATTERN.matcher(instanceId);
+ if (!matcher.matches()) {
+ matcher = PATTERN_DEPRECATED.matcher(instanceId);
}
- Preconditions.checkArgument(matcher.matches(), "Unexpected format for provider, expected " + p.toString()
- + " or " + pDeprecated.toString() + " but was " + instanceId);
+ Preconditions.checkArgument(matcher.matches(),
+ "Unexpected format for provider, expected " + PATTERN.toString()
+ + " or " + PATTERN_DEPRECATED.toString() + " but was " + instanceId);
String factoryName = matcher.group(1);
String instanceName = matcher.group(2);
return new ServiceInstance(factoryName, instanceName);
}
- private final String moduleName, instanceName;
+ private final String moduleName;
+ private final String instanceName;
+
private String serviceName;
public String getServiceName() {
return instanceName;
}
- private static final String blueprint = "/"
- + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "["
- + XmlMappingConstants.TYPE_KEY + "='%s']["
+ private static final String BLUEPRINT = "/" + XmlMappingConstants.MODULES_KEY + "/"
+ + XmlMappingConstants.MODULE_KEY + "[" + XmlMappingConstants.TYPE_KEY + "='%s']["
+ XmlMappingConstants.NAME_KEY + "='%s']";
// TODO unify with xpath in RuntimeRpc
- // Previous version of xpath, needs to be supported for backwards compatibility (persisted configs by config-persister)
- private static final String blueprintRDeprecated = "/" + XmlMappingConstants.CONFIG_KEY + "/"
+ // Previous version of xpath, needs to be supported for backwards compatibility
+ // (persisted configs by config-persister)
+ private static final String BLUEPRINTR_DEPRECATED = "/" + XmlMappingConstants.CONFIG_KEY + "/"
+ XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "\\["
+ XmlMappingConstants.NAME_KEY + "='%s'\\]/" + XmlMappingConstants.INSTANCE_KEY + "\\["
+ XmlMappingConstants.NAME_KEY + "='%s'\\]";
- private static final String blueprintR = "/"
- + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "\\["
- + XmlMappingConstants.TYPE_KEY + "='%s'\\]\\["
+ private static final String BLUEPRINTR = "/" + XmlMappingConstants.MODULES_KEY + "/"
+ + XmlMappingConstants.MODULE_KEY + "\\[" + XmlMappingConstants.TYPE_KEY + "='%s'\\]\\["
+ XmlMappingConstants.NAME_KEY + "='%s'\\]";
- private static final Pattern pDeprecated = Pattern.compile(String.format(blueprintRDeprecated, "(.+)", "(.+)"));
- private static final Pattern p = Pattern.compile(String.format(blueprintR, "(.+)", "(.+)"));
+ private static final Pattern PATTERN_DEPRECATED =
+ Pattern.compile(String.format(BLUEPRINTR_DEPRECATED, "(.+)", "(.+)"));
+ private static final Pattern PATTERN = Pattern.compile(String.format(BLUEPRINTR, "(.+)", "(.+)"));
@Override
public String toString() {
- return String.format(blueprint, moduleName, instanceName);
+ return String.format(BLUEPRINT, moduleName, instanceName);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((instanceName == null) ? 0 : instanceName.hashCode());
- result = prime * result + ((moduleName == null) ? 0 : moduleName.hashCode());
+ result = prime * result + (instanceName == null ? 0 : instanceName.hashCode());
+ result = prime * result + (moduleName == null ? 0 : moduleName.hashCode());
return result;
}
@Override
public boolean equals(final 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;
}
ServiceInstance other = (ServiceInstance) obj;
if (instanceName == null) {
- if (other.instanceName != null){
+ if (other.instanceName != null) {
return false;
}
- } else if (!instanceName.equals(other.instanceName)){
+ } else if (!instanceName.equals(other.instanceName)) {
return false;
}
if (moduleName == null) {
- if (other.moduleName != null){
+ if (other.moduleName != null) {
return false;
}
- } else if (!moduleName.equals(other.moduleName)){
+ } else if (!moduleName.equals(other.moduleName)) {
return false;
}
return true;
return new ServiceInstance(ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));
}
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.slf4j.LoggerFactory;
/**
- * Start yang store service and the XML config manager facade
+ * Start yang store service and the XML config manager facade.
*/
public class YangStoreActivator implements BundleActivator {
LOG.debug("ConfigPersister starting");
this.context = context;
- final ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService>() {
+ final ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService> schemaServiceTrackerCustomizer =
+ new ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService>() {
private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
@Override
public YangStoreService addingService(final ServiceReference<SchemaContextProvider> reference) {
LOG.debug("Got addingService(SchemaContextProvider) event");
- if((reference.getProperty(SchemaSourceProvider.class.getName()) == null) &&
- (reference.getProperty(BindingRuntimeContext.class.getName()) == null)) {
+ if (reference.getProperty(SchemaSourceProvider.class.getName()) == null
+ && reference.getProperty(BindingRuntimeContext.class.getName()) == null) {
LOG.debug("SchemaContextProvider not from config-manager. Ignoring");
return null;
}
// Yang store service should not be registered multiple times
- if(!this.alreadyStarted.compareAndSet(false, true)) {
+ if (!this.alreadyStarted.compareAndSet(false, true)) {
LOG.warn("Starting yang store service multiple times. Received new service {}", reference);
throw new RuntimeException("Starting yang store service multiple times");
}
- final SchemaContextProvider schemaContextProvider = reference.getBundle().getBundleContext().getService(reference);
+ final SchemaContextProvider schemaContextProvider = reference.getBundle().getBundleContext()
+ .getService(reference);
final Object sourceProvider = Preconditions.checkNotNull(
- reference.getProperty(SchemaSourceProvider.class.getName()), "Source provider not found");
+ reference.getProperty(SchemaSourceProvider.class.getName()), "Source provider not found");
Preconditions.checkArgument(sourceProvider instanceof SchemaSourceProvider);
// TODO avoid cast
final YangStoreService yangStoreService = new YangStoreService(schemaContextProvider,
- ((SchemaSourceProvider<YangTextSchemaSource>) sourceProvider));
+ (SchemaSourceProvider<YangTextSchemaSource>) sourceProvider);
final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference
.getProperty(BindingRuntimeContext.class.getName());
LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
- if(runtimeContext != null) {
+ if (runtimeContext != null) {
yangStoreService.refresh(runtimeContext);
}
- YangStoreActivator.this.yangStoreServiceServiceRegistration = context.registerService(YangStoreService.class, yangStoreService,
- new Hashtable<>());
+ YangStoreActivator.this.yangStoreServiceServiceRegistration = context
+ .registerService(YangStoreService.class, yangStoreService, new Hashtable<>());
YangStoreActivator.this.configRegistryLookup = new ConfigRegistryLookupThread(yangStoreService);
YangStoreActivator.this.configRegistryLookup.start();
return yangStoreService;
}
@Override
- public void modifiedService(final ServiceReference<SchemaContextProvider> reference, final YangStoreService service) {
+ public void modifiedService(final ServiceReference<SchemaContextProvider> reference,
+ final YangStoreService service) {
if (service == null) {
return;
}
LOG.debug("Got modifiedService(SchemaContextProvider) event");
final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference
- .getProperty(BindingRuntimeContext.class.getName());
+ .getProperty(BindingRuntimeContext.class.getName());
LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
service.refresh(runtimeContext);
}
@Override
- public void removedService(final ServiceReference<SchemaContextProvider> reference, final YangStoreService service) {
- if(service == null) {
+ public void removedService(final ServiceReference<SchemaContextProvider> reference,
+ final YangStoreService service) {
+ if (service == null) {
return;
}
@Override
public void stop(final BundleContext context) throws Exception {
- if(this.configRegistryLookup != null) {
+ if (this.configRegistryLookup != null) {
this.configRegistryLookup.interrupt();
}
- if(this.osgiRegistrayion != null) {
+ if (this.osgiRegistrayion != null) {
this.osgiRegistrayion.unregister();
}
if (this.yangStoreServiceServiceRegistration != null) {
}
/**
- * Find ConfigRegistry from config manager in JMX
+ * Find ConfigRegistry from config manager in JMX.
*/
private class ConfigRegistryLookupThread extends Thread {
public static final int ATTEMPT_TIMEOUT_MS = 1000;
ConfigRegistryJMXClient configRegistryJMXClient;
ConfigRegistryJMXClient configRegistryJMXClientNoNotifications;
- int i = 0;
+ int index = 0;
// Config registry might not be present yet, but will be eventually
- while(true) {
+ while (true) {
try {
configRegistryJMXClient = new ConfigRegistryJMXClient(YangStoreActivator.this.configMBeanServer);
- configRegistryJMXClientNoNotifications = ConfigRegistryJMXClient.createWithoutNotifications(YangStoreActivator.this.configMBeanServer);
+ configRegistryJMXClientNoNotifications = ConfigRegistryJMXClient
+ .createWithoutNotifications(YangStoreActivator.this.configMBeanServer);
break;
} catch (final IllegalStateException e) {
- ++i;
- if (i > SILENT_ATTEMPTS) {
- LOG.info("JMX client not created after {} attempts, still trying", i, e);
+ ++index;
+ if (index > SILENT_ATTEMPTS) {
+ LOG.info("JMX client not created after {} attempts, still trying", index, e);
} else {
- LOG.debug("JMX client could not be created, reattempting, try {}", i, e);
+ LOG.debug("JMX client could not be created, reattempting, try {}", index, e);
}
try {
Thread.sleep(ATTEMPT_TIMEOUT_MS);
final ConfigRegistryJMXClient jmxClient = configRegistryJMXClient;
final ConfigRegistryJMXClient jmxClientNoNotifications = configRegistryJMXClientNoNotifications;
- if (i > SILENT_ATTEMPTS) {
- LOG.info("Created JMX client after {} attempts", i);
+ if (index > SILENT_ATTEMPTS) {
+ LOG.info("Created JMX client after {} attempts", index);
} else {
- LOG.debug("Created JMX client after {} attempts", i);
+ LOG.debug("Created JMX client after {} attempts", index);
}
- final ConfigSubsystemFacadeFactory configSubsystemFacade =
- new ConfigSubsystemFacadeFactory(jmxClient, jmxClientNoNotifications, this.yangStoreService);
- YangStoreActivator.this.osgiRegistrayion = YangStoreActivator.this.context.registerService(ConfigSubsystemFacadeFactory.class, configSubsystemFacade,
- new Hashtable<>());
+ final ConfigSubsystemFacadeFactory configSubsystemFacade = new ConfigSubsystemFacadeFactory(jmxClient,
+ jmxClientNoNotifications, this.yangStoreService);
+ YangStoreActivator.this.osgiRegistrayion = YangStoreActivator.this.context
+ .registerService(ConfigSubsystemFacadeFactory.class, configSubsystemFacade, new Hashtable<>());
}
}
}
-
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public interface YangStoreContext {
/**
- * @deprecated Use {@link #getQNamesToIdentitiesToModuleMXBeanEntries()} instead. This method return only one
- * module representation even if multiple revisions are available.
+ * Yang store context.
+ *
+ * @deprecated Use {@link #getQNamesToIdentitiesToModuleMXBeanEntries()}
+ * instead. This method return only one module representation even
+ * if multiple revisions are available.
*/
@Deprecated
Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> getModuleMXBeanEntryMap();
-
+ Map<String /* Name of module entry from yang file */,
+ ModuleMXBeanEntry>> getModuleMXBeanEntryMap();
Map<QName, Map<String /* identity local name */, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries();
/**
* Get all modules discovered when this snapshot was created.
- * @return all modules discovered. If one module exists with two different revisions, return both.
+ *
+ * @return all modules discovered. If one module exists with two different
+ * revisions, return both.
*/
Set<Module> getModules();
String getModuleSource(ModuleIdentifier moduleIdentifier);
EnumResolver getEnumResolver();
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
package org.opendaylight.controller.config.facade.xml.osgi;
-import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(
- new ThreadFactoryBuilder().setDaemon(true).setNameFormat("yangstore-capability-notifications").build());
+ new ThreadFactoryBuilder().setDaemon(true).setNameFormat("yangstore-capability-notifications").build());
/**
- * Guarded by explicit lock to allow for properly synchronizing the initial notification and modification
- * of the listener set.
+ * Guarded by explicit lock to allow for properly synchronizing the initial
+ * notification and modification of the listener set.
*/
@GuardedBy("listeners")
private final Set<ModuleListener> listeners = new HashSet<>();
/**
- * This is the latest snapshot. Some of its state is always initialized, but the MXBean maps potentially cause
- * recomputation. Accessing those two specific methods needs to re-check whether the snapshot has changed
- * asynchronously and retry if it didi.
+ * This is the latest snapshot. Some of its state is always initialized, but the
+ * MXBean maps potentially cause recomputation. Accessing those two specific
+ * methods needs to re-check whether the snapshot has changed asynchronously and
+ * retry if it didi.
*/
private volatile YangStoreSnapshot snap;
public YangStoreService(final SchemaContextProvider schemaContextProvider,
- final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
+ final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
this.sourceProvider = sourceProvider;
}
final YangStoreSnapshot next = new YangStoreSnapshot(runtimeContext, this.sourceProvider);
final YangStoreSnapshot previous = this.snap;
this.snap = next;
- this.notificationExecutor.submit(new Runnable() {
- @Override
- public void run() {
- notifyListeners(previous, next);
- }
- });
+ this.notificationExecutor.submit(() -> notifyListeners(previous, next));
}
public AutoCloseable registerModuleListener(final ModuleListener listener) {
synchronized (this.listeners) {
if (context != null) {
- listener.onCapabilitiesChanged(toCapabilities(context.getModules(), context), Collections.<Capability>emptySet());
+ listener.onCapabilitiesChanged(toCapabilities(context.getModules(), context),
+ Collections.<Capability>emptySet());
}
this.listeners.add(listener);
}
- return new AutoCloseable() {
- @Override
- public void close() {
- synchronized (YangStoreService.this.listeners) {
- YangStoreService.this.listeners.remove(listener);
- }
+ return () -> {
+ synchronized (YangStoreService.this.listeners) {
+ YangStoreService.this.listeners.remove(listener);
}
};
}
}
private static Set<Capability> toCapabilities(final Set<Module> modules, final YangStoreContext current) {
- return ImmutableSet.copyOf(Collections2.transform(modules, new Function<Module, Capability>() {
- @Override
- public Capability apply(final Module input) {
- return new YangModuleCapability(input, current.getModuleSource(input));
- }
- }));
+ return ImmutableSet.copyOf(Collections2.transform(modules,
+ input -> new YangModuleCapability(input, current.getModuleSource(input))));
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class YangStoreSnapshot implements YangStoreContext, EnumResolver {
+public final class YangStoreSnapshot implements YangStoreContext, EnumResolver {
private static final class MXBeans {
private final Map<String /* Namespace from yang file */,
Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
- private final Map<QName, Map<String, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries;
+ private final Map<QName, Map<String, ModuleMXBeanEntry>> namesToIdentitiesToModuleMXBeanEntries;
MXBeans(final SchemaContext schemaContext) {
LOG.trace("Resolved modules:{}", schemaContext.getModules());
.create(module, packageName, knownSEITracker);
for (final Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries.entrySet()) {
// merge value into qNamesToSIEs
- if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
+ if (!qNamesToSIEs.containsKey(sieEntry.getKey())) {
qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
} else {
throw new IllegalStateException("Cannot add two SIE with same qname "
final Map<String, Map<String, ModuleMXBeanEntry>> moduleMXBeanEntryMap = Maps.newHashMap();
- final Map<QName, Map<String /* identity local name */, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries = new HashMap<>();
+ final Map<QName, Map<String /* identity local name */,
+ ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries = new HashMap<>();
for (final Module module : schemaContext.getModules()) {
qNamesToIdentitiesToModuleMXBeanEntries.put(qName, namesToMBEs);
}
this.moduleMXBeanEntryMap = Collections.unmodifiableMap(moduleMXBeanEntryMap);
- this.qNamesToIdentitiesToModuleMXBeanEntries = Collections.unmodifiableMap(qNamesToIdentitiesToModuleMXBeanEntries);
+ this.namesToIdentitiesToModuleMXBeanEntries =
+ Collections.unmodifiableMap(qNamesToIdentitiesToModuleMXBeanEntries);
}
}
@Override
public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
- return getMXBeans().qNamesToIdentitiesToModuleMXBeanEntries;
+ return getMXBeans().namesToIdentitiesToModuleMXBeanEntries;
}
@Override
@Override
public String getModuleSource(final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
- final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source = this.sourceProvider.getSource(
- SourceIdentifier.create(moduleIdentifier.getName(), Optional.fromNullable(
- QName.formattedRevision(moduleIdentifier.getRevision()))));
+ final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source = this.sourceProvider
+ .getSource(SourceIdentifier.create(moduleIdentifier.getName(),
+ Optional.fromNullable(QName.formattedRevision(moduleIdentifier.getRevision()))));
try {
final YangTextSchemaSource yangTextSchemaSource = source.checkedGet();
- try(InputStream inStream = yangTextSchemaSource.openStream()) {
+ try (InputStream inStream = yangTextSchemaSource.openStream()) {
return new String(ByteStreams.toByteArray(inStream), StandardCharsets.UTF_8);
}
} catch (SchemaSourceException | IOException e) {
Preconditions.checkState(this.bindingContextProvider != null, "Binding context provider was not set yet");
final BiMap<String, String> enumMapping = this.bindingContextProvider.getEnumMapping(enumClass);
final String javaName = enumMapping.get(enumYangValue);
- return Preconditions.checkNotNull(javaName, "Unable to resolve enum value %s for enum class %s with assumed enum mapping: %s", enumYangValue, enumClass, enumMapping);
+ return Preconditions.checkNotNull(javaName,
+ "Unable to resolve enum value %s for enum class %s with assumed enum mapping: %s", enumYangValue,
+ enumClass, enumMapping);
}
@Override
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
.get(configDefEntry.getKey());
configDefEntry.getValue().resolveValue(attributeResolvingStrategy, configDefEntry.getKey());
- configDefEntry.getValue().setJmxName(
- yangToAttrConfig.get(configDefEntry.getKey()).getUpperCaseCammelCase());
- } catch (final Exception e) {
+ configDefEntry.getValue()
+ .setJmxName(yangToAttrConfig.get(configDefEntry.getKey()).getUpperCaseCammelCase());
+ } catch (final DocumentedException e) {
throw new IllegalStateException("Unable to resolve value " + configDefEntry.getValue()
+ " to attribute " + configDefEntry.getKey(), e);
}
// FIXME add identity map to runtime data
Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig,
- Collections.<String, Map<Date, IdentityMapping>> emptyMap());
+ Collections.<String, Map<Date, IdentityMapping>>emptyMap());
for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
List<XmlElement> configNodes = configRootNode.getChildElements(readStratEntry.getKey());
public AttributeIfc getReturnType() {
return rpc.getReturnType();
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module;
/**
- * Represents parsed xpath to runtime bean instance
+ * Represents parsed xpath to runtime bean instance.
*/
public final class RuntimeRpcElementResolved {
private final String moduleName;
private final Map<String, String> additionalAttributes;
private RuntimeRpcElementResolved(String namespace, String moduleName, String instanceName, String runtimeBeanName,
- Map<String, String> additionalAttributes) {
+ Map<String, String> additionalAttributes) {
this.moduleName = Preconditions.checkNotNull(moduleName, "Module name");
- this.instanceName = Preconditions.checkNotNull(instanceName, "Instance name");
+ this.instanceName = Preconditions.checkNotNull(instanceName, "Instance name");
this.additionalAttributes = additionalAttributes;
this.namespace = Preconditions.checkNotNull(namespace, "Namespace");
this.runtimeBeanName = Preconditions.checkNotNull(runtimeBeanName, "Runtime bean name");
}
/**
- * Pattern for an absolute instance identifier xpath pointing to a runtime bean instance e.g:
+ * Pattern for an absolute instance identifier xpath pointing to a runtime bean.
+ * For instance e.g:
+ *
* <pre>
* /modules/module[name=instanceName][type=moduleType]
* </pre>
+ *
+ *<p>
* or
+ *
* <pre>
* /a:modules/a:module[a:name=instanceName][a:type=moduleType]
* </pre>
*/
- private static final String xpathPatternBlueprint =
- "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())+ "/" + getRegExForPrefixedName(Module.QNAME.getLocalName())
+ private static final String XPATH_PATTERN_BLUEPRINT = "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())
+ + "/" + getRegExForPrefixedName(Module.QNAME.getLocalName())
- + "\\["
- + "(?<key1>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")"
- + "=('|\")?(?<value1>[^'\"\\]]+)('|\")?"
- + "( and |\\]\\[)"
- + "(?<key2>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")"
- + "=('|\")?(?<value2>[^'\"\\]]+)('|\")?"
- + "\\]"
+ + "\\[" + "(?<key1>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|"
+ + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?<value1>[^'\"\\]]+)('|\")?"
+ + "( and |\\]\\[)" + "(?<key2>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|"
+ + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?<value2>[^'\"\\]]+)('|\")?"
+ + "\\]"
- + "(?<additional>.*)";
+ + "(?<additional>.*)";
/**
- * Return reg ex that matches either the name with or without a prefix
+ * Return reg ex that matches either the name with or without a prefix.
*/
private static String getRegExForPrefixedName(final String name) {
return "([^:]+:)?" + name;
}
- private static final Pattern xpathPattern = Pattern.compile(xpathPatternBlueprint);
+ private static final Pattern XPATH_PATTERN = Pattern.compile(XPATH_PATTERN_BLUEPRINT);
/**
- * Pattern for additional path elements inside xpath for instance identifier pointing to an inner runtime bean e.g:
+ * Pattern for additional path elements inside xpath for instance identifier
+ * pointing to an inner runtime bean. E.g:
+ *
* <pre>
* /modules/module[name=instanceName and type=moduleType]/inner[key=b]
* </pre>
*/
- private static final String additionalPatternBlueprint = getRegExForPrefixedName("(?<additionalKey>.+)") + "\\[(?<prefixedKey>" + getRegExForPrefixedName("(.+)") + ")=('|\")?(?<additionalValue>[^'\"\\]]+)('|\")?\\]";
- private static final Pattern additionalPattern = Pattern.compile(additionalPatternBlueprint);
+ private static final String ADDITIONAL_PATTERN_BLUEPRINT = getRegExForPrefixedName("(?<additionalKey>.+)")
+ + "\\[(?<prefixedKey>" + getRegExForPrefixedName("(.+)")
+ + ")=('|\")?(?<additionalValue>[^'\"\\]]+)('|\")?\\]";
+ private static final Pattern ADDITIONAL_PATTERN = Pattern.compile(ADDITIONAL_PATTERN_BLUEPRINT);
public static RuntimeRpcElementResolved fromXpath(String xpath, String elementName, String namespace) {
- Matcher matcher = xpathPattern.matcher(xpath);
+ Matcher matcher = XPATH_PATTERN.matcher(xpath);
Preconditions.checkState(matcher.matches(),
"Node %s with value '%s' not in required form on rpc element %s, required format is %s",
- //TODO refactor this string, and/or unify with RPR.CONTEXT_INSTANCE from netconf
- "context-instance", xpath, elementName, xpathPatternBlueprint);
+ // TODO refactor this string, and/or unify with RPR.CONTEXT_INSTANCE from
+ // netconf
+ "context-instance", xpath, elementName, XPATH_PATTERN_BLUEPRINT);
PatternGroupResolver groups = new PatternGroupResolver(matcher.group("key1"), matcher.group("value1"),
matcher.group("value2"), matcher.group("additional"));
private static final class PatternGroupResolver {
- private final String key1, value1, value2;
+ private final String key1;
+ private final String value1;
+ private final String value2;
private final String additional;
private String runtimeBeanYangName;
- PatternGroupResolver(String key1, String value1, String value2, String additional) {
+ PatternGroupResolver(String key1, String value1, String value2, String additional) {
this.key1 = Preconditions.checkNotNull(key1);
this.value1 = Preconditions.checkNotNull(value1);
this.value2 = Preconditions.checkNotNull(value2);
return key1.contains(XmlMappingConstants.NAME_KEY) ? value1 : value2;
}
-
Map<String, String> getAdditionalKeys(String elementName, String moduleName) {
HashMap<String, String> additionalAttributes = Maps.newHashMap();
runtimeBeanYangName = moduleName;
for (String additionalKeyValue : additional.split("/")) {
- if (Strings.isNullOrEmpty(additionalKeyValue)){
+ if (Strings.isNullOrEmpty(additionalKeyValue)) {
continue;
}
- Matcher matcher = additionalPattern.matcher(additionalKeyValue);
- Preconditions
- .checkState(
- matcher.matches(),
- "Attribute %s not in required form on rpc element %s, required format for additional attributes is: %s",
- additionalKeyValue, elementName, additionalPatternBlueprint);
+ Matcher matcher = ADDITIONAL_PATTERN.matcher(additionalKeyValue);
+ Preconditions.checkState(matcher.matches(),
+ "Attribute %s not in required form on rpc element %s,"
+ + " required format for additional attributes is: %s",
+ additionalKeyValue, elementName, ADDITIONAL_PATTERN_BLUEPRINT);
String name = matcher.group("additionalKey");
runtimeBeanYangName = name;
additionalAttributes.put(name, matcher.group("additionalValue"));
}
private String getRuntimeBeanYangName() {
- Preconditions.checkState(runtimeBeanYangName!=null);
+ Preconditions.checkState(runtimeBeanYangName != null);
return runtimeBeanYangName;
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
package org.opendaylight.controller.config.facade.xml.runtime;
import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
import java.util.Map;
public class InstanceRuntime {
- /**
- *
- */
private static final String KEY_ATTRIBUTE_KEY = "key";
private final InstanceConfig instanceMapping;
}
/**
- * Finds all children runtime beans, same properties and values as current
- * root + any number of additional properties
+ * Finds all children runtime beans, same properties and values as current root
+ * + any number of additional properties.
*/
private Set<ObjectName> findChildren(ObjectName innerRootBean, Set<ObjectName> childRbeOns) {
final Map<String, String> wantedProperties = innerRootBean.getKeyPropertyList();
- return Sets.newHashSet(Collections2.filter(childRbeOns, new Predicate<ObjectName>() {
-
- @Override
- public boolean apply(ObjectName on) {
- Map<String, String> localProperties = on.getKeyPropertyList();
- for (Entry<String, String> propertyEntry : wantedProperties.entrySet()) {
- if (!localProperties.containsKey(propertyEntry.getKey())){
- return false;
- }
- if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue())){
- return false;
- }
- if (localProperties.size() <= wantedProperties.size()){
- return false;
- }
+ return Sets.newHashSet(Collections2.filter(childRbeOns, on -> {
+ Map<String, String> localProperties = on.getKeyPropertyList();
+ for (Entry<String, String> propertyEntry : wantedProperties.entrySet()) {
+ if (!localProperties.containsKey(propertyEntry.getKey())) {
+ return false;
+ }
+ if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue())) {
+ return false;
+ }
+ if (localProperties.size() <= wantedProperties.size()) {
+ return false;
}
- return true;
}
+ return true;
}));
}
/**
- * Finds next level root runtime beans, beans that have the same properties
- * as current root + one additional
+ * Finds next level root runtime beans, beans that have the same properties as
+ * current root + one additional.
*/
private Set<ObjectName> getRootBeans(Set<ObjectName> childRbeOns, final String string, final int keyListSize) {
- return Sets.newHashSet(Collections2.filter(childRbeOns, new Predicate<ObjectName>() {
-
- @Override
- public boolean apply(ObjectName on) {
- if (on.getKeyPropertyList().size() != keyListSize + 1){
- return false;
- }
- return on.getKeyPropertyList().containsKey(string);
+ return Sets.newHashSet(Collections2.filter(childRbeOns, on -> {
+ if (on.getKeyPropertyList().size() != keyListSize + 1) {
+ return false;
}
+ return on.getKeyPropertyList().containsKey(string);
}));
}
- public Element toXml(ObjectName rootOn, Set<ObjectName> childRbeOns, Document document, Element parentElement, String namespace, final EnumResolver enumResolver) {
+ public Element toXml(ObjectName rootOn, Set<ObjectName> childRbeOns, Document document, Element parentElement,
+ String namespace, final EnumResolver enumResolver) {
return toXml(rootOn, childRbeOns, document, null, parentElement, namespace, enumResolver);
}
public Element toXml(ObjectName rootOn, Set<ObjectName> childRbeOns, Document document, String instanceIndex,
- Element parentElement, String namespace, final EnumResolver enumResolver) {
+ Element parentElement, String namespace, final EnumResolver enumResolver) {
Element xml = instanceMapping.toXml(rootOn, namespace, document, parentElement, enumResolver);
if (instanceIndex != null) {
}
for (Entry<String, InstanceRuntime> childMappingEntry : childrenMappings.entrySet()) {
- Set<ObjectName> innerRootBeans = getRootBeans(childRbeOns, childMappingEntry.getKey(), rootOn
- .getKeyPropertyList().size());
+ Set<ObjectName> innerRootBeans = getRootBeans(childRbeOns, childMappingEntry.getKey(),
+ rootOn.getKeyPropertyList().size());
for (ObjectName objectName : innerRootBeans) {
Set<ObjectName> innerChildRbeOns = findChildren(objectName, childRbeOns);
String elementName = jmxToYangChildRbeMapping.get(childMappingEntry.getKey());
Element innerXml = XmlUtil.createElement(document, elementName, Optional.of(namespace));
- childMappingEntry.getValue().toXml(objectName, innerChildRbeOns, document,
- runtimeInstanceIndex, innerXml, namespace, enumResolver);
+ childMappingEntry.getValue().toXml(objectName, innerChildRbeOns, document, runtimeInstanceIndex,
+ innerXml, namespace, enumResolver);
xml.appendChild(innerXml);
}
}
-
return xml;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private ObjectName findRoot(Collection<ObjectName> runtimeBeanOns) {
for (ObjectName objectName : runtimeBeanOns) {
- if (objectName.getKeyPropertyList().size() == 3){
+ if (objectName.getKeyPropertyList().size() == 3) {
return objectName;
}
}
throw new IllegalStateException("Root runtime bean not found among " + runtimeBeanOns);
}
- public Element toXml(String namespace, Collection<ObjectName> runtimeBeanOns,
- Document document, ModuleConfig moduleConfig, ObjectName configBeanON, final EnumResolver enumResolver) {
+ public Element toXml(String namespace, Collection<ObjectName> runtimeBeanOns, Document document,
+ ModuleConfig moduleConfig, ObjectName configBeanON, final EnumResolver enumResolver) {
Element moduleElement = moduleConfig.toXml(configBeanON, document, namespace, enumResolver);
return moduleElement;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
multimap.put(instanceName, objectName);
}
-
return retVal;
}
- public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document, final EnumResolver enumResolver) {
+ public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document,
+ final EnumResolver enumResolver) {
Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
- Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
+ Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
+ Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
root.appendChild(modulesElement);
Map<String, Multimap<String, ObjectName>> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap);
- Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config
- .getMappedInstances(configBeans, moduleConfigs);
+ Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config.getMappedInstances(configBeans,
+ moduleConfigs);
for (String localNamespace : moduleConfigs.keySet()) {
Element runtimeXml;
ModuleConfig moduleConfig = moduleConfigs.get(localNamespace).get(moduleName);
- if(instanceToRbe==null || !instanceToRbe.containsKey(instanceName)) {
+ if (instanceToRbe == null || !instanceToRbe.containsKey(instanceName)) {
runtimeXml = moduleConfig.toXml(instanceON, document, localNamespace, enumResolver);
} else {
ModuleRuntime moduleRuntime = moduleRuntimes.get(localNamespace).get(moduleName);
}
}
-
return root;
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private static final Logger LOG = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
-
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
- throw new ConfigHandlingException(String.format("Unable to delete %s : %s , ServiceInstance not found", module, instance),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
+ throw new ConfigHandlingException(
+ String.format("Unable to delete %s : %s , ServiceInstance not found", module, instance),
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
+ ServiceRegistryWrapper services) throws ConfigHandlingException {
try {
ta.destroyModule(on);
LOG.debug("ServiceInstance {} deleted successfully", on);
} catch (InstanceNotFoundException e) {
throw new ConfigHandlingException(
String.format("Unable to delete %s because of exception %s" + on, e.getMessage()),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
// additional per element
delete, remove, recreate;
- private static final Set<EditStrategyType> defaultStrats = EnumSet.of(merge, replace, none);
+ private static final Set<EditStrategyType> DEFAULT_STRATS = EnumSet.of(merge, replace, none);
public static EditStrategyType getDefaultStrategy() {
return merge;
public boolean isEnforcing() {
switch (this) {
- case merge:
- case none:
- case remove:
- case delete:
- case recreate:
- return false;
- case replace:
- return true;
+ case merge:
+ case none:
+ case remove:
+ case delete:
+ case recreate:
+ return false;
+ case replace:
+ return true;
- default:
- throw new IllegalStateException("Default edit strategy can be only of value " + defaultStrats + " but was "
- + this);
+ default:
+ throw new IllegalStateException(
+ "Default edit strategy can be only of value " + DEFAULT_STRATS + " but was " + this);
}
}
+
public static void compareParsedStrategyToDefaultEnforcing(EditStrategyType parsedStrategy,
- EditStrategyType defaultStrategy) throws OperationNotPermittedException {
+ EditStrategyType defaultStrategy) throws OperationNotPermittedException {
if (defaultStrategy.isEnforcing()) {
- if (parsedStrategy != defaultStrategy){
- throw new OperationNotPermittedException(String.format("With "
- + defaultStrategy
- + " as default-operation operations on module elements are not permitted since the default option is restrictive"),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ if (parsedStrategy != defaultStrategy) {
+ throw new OperationNotPermittedException(String.format("With " + defaultStrategy
+ + " as default-operation operations on module elements are not permitted"
+ + "since the default option is restrictive"),
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
-
}
+
public EditConfigStrategy getFittingStrategy() {
switch (this) {
- case merge:
- return new MergeEditConfigStrategy();
- case replace:
- return new ReplaceEditConfigStrategy();
- case delete:
- return new DeleteEditConfigStrategy();
- case remove:
- return new RemoveEditConfigStrategy();
- case recreate:
- return new ReCreateEditConfigStrategy();
- case none:
- return new NoneEditConfigStrategy();
- default:
- throw new UnsupportedOperationException("Unimplemented edit config strategy" + this);
+ case merge:
+ return new MergeEditConfigStrategy();
+ case replace:
+ return new ReplaceEditConfigStrategy();
+ case delete:
+ return new DeleteEditConfigStrategy();
+ case remove:
+ return new RemoveEditConfigStrategy();
+ case recreate:
+ return new ReCreateEditConfigStrategy();
+ case none:
+ return new NoneEditConfigStrategy();
+ default:
+ throw new UnsupportedOperationException("Unimplemented edit config strategy" + this);
}
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
private static final Logger LOG = LoggerFactory.getLogger(MergeEditConfigStrategy.class);
public MergeEditConfigStrategy() {
-
}
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
- throw new ConfigHandlingException(
- String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
- module,
- instance),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
+ String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
+ throw new ConfigHandlingException(String.format(
+ "Unable to handle missing instance, no missing instances should "
+ + "appear at this point, missing: %s : %s ",
+ module, instance), DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
+ @SuppressWarnings("IllegalCatch")
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
+ ServiceRegistryWrapper services) throws ConfigHandlingException {
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
try {
Object toBeMergedIn = ace.getResolvedValue().get();
// Get the existing values so we can merge the new values with them.
Attribute currentAttribute = ta.getAttribute(on, ace.getJmxName());
- Object oldValue = (currentAttribute != null ? currentAttribute.getValue() : null);
+ Object oldValue = currentAttribute != null ? currentAttribute.getValue() : null;
// Merge value with currentValue
toBeMergedIn = merge(oldValue, toBeMergedIn);
ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), toBeMergedIn));
LOG.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), toBeMergedIn, on);
- } catch (Exception e) {
- LOG.error("Error while merging objectnames of {}", on, e);
- throw new ConfigHandlingException(String.format("Unable to set attributes for %s, Error with attribute %s : %s ",
+ } catch (RuntimeException e) {
+ LOG.error("Error while merging object names of {}", on, e);
+ throw new ConfigHandlingException(String.format("Unable to set attributes for %s, "
+ + "Error with attribute %s : %s ",
on,
configAttributeEntry.getKey(),
configAttributeEntry.getValue()),
}
/**
- * Merge value into current value
- * Currently, this is only implemented for arrays of ObjectNames, but that is the
- * most common case for which it is needed.
+ * Merge value into current value Currently, this is only implemented for arrays
+ * of ObjectNames, but that is the most common case for which it is needed.
*/
protected Object merge(Object oldValue, Object toBeMergedIn) {
if (oldValue instanceof ObjectName[] && toBeMergedIn instanceof ObjectName[]) {
}
/**
- * Merge value into current values
- * This implements for arrays of ObjectNames, but that is the
- * most common case for which it is needed.
+ * Merge value into current values This implements for arrays of ObjectNames,
+ * but that is the most common case for which it is needed.
*
- * @param oldValue - the new values to be merged into existing values
- * @param toBeMergedIn - the existing values
+ * @param oldValue
+ * - the new values to be merged into existing values
+ * @param toBeMergedIn
+ * - the existing values
*
- * @return an ObjectName[] consisting the elements of currentValue with an elements from values not already present in currentValue added
+ * @return an ObjectName[] consisting the elements of currentValue with an
+ * elements from values not already present in currentValue added
*
*/
protected ObjectName[] mergeObjectNameArrays(ObjectName[] oldValue, ObjectName[] toBeMergedIn) {
List<ObjectName> newValueList = new ArrayList<>();
newValueList.addAll(asList(oldValue));
/*
- It is guaranteed that old values do not contain transaction name.
- Since toBeMergedIn is filled using service references translated by ServiceRegistryWrapper, it
- is also guaranteed that this list will not contain transaction names.
- Run through the list of values to be merged. If we don't have them already, add them to the list.
+ * It is guaranteed that old values do not contain transaction name. Since
+ * toBeMergedIn is filled using service references translated by
+ * ServiceRegistryWrapper, it is also guaranteed that this list will not contain
+ * transaction names. Run through the list of values to be merged. If we don't
+ * have them already, add them to the list.
*/
for (ObjectName objName : toBeMergedIn) {
if (!newValueList.contains(objName)) {
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
- if(configuration != null && !configuration.isEmpty()) {
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws ConfigHandlingException {
+ if (configuration != null && !configuration.isEmpty()) {
for (Map.Entry<String, AttributeConfigElement> attrEntry : configuration.entrySet()) {
- if(attrEntry.getValue().getEditStrategy().isPresent()) {
- final Map<String, AttributeConfigElement> partialConfig =
- Collections.singletonMap(attrEntry.getKey(), attrEntry.getValue());
- attrEntry.getValue().getEditStrategy().get().getFittingStrategy()
- .executeConfiguration(module, instance, partialConfig, ta, services);
+ if (attrEntry.getValue().getEditStrategy().isPresent()) {
+ final Map<String, AttributeConfigElement> partialConfig = Collections
+ .singletonMap(attrEntry.getKey(), attrEntry.getValue());
+ attrEntry.getValue().getEditStrategy().get().getFittingStrategy().executeConfiguration(module,
+ instance, partialConfig, ta, services);
} else {
LOG.debug("Skipping configuration element for {}:{}:{}", module, instance, attrEntry.getKey());
}
LOG.debug("Skipping configuration element for {}:{}", module, instance);
}
}
-
}
/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2016, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.controller.config.util.xml.DocumentedException;
/**
- * Edit strategy that forces re-creation of a module instance even if the config didn't change.
+ * Edit strategy that forces re-creation of a module instance even if the config
+ * didn't change.
*
* @author Thomas Pantelis
*/
String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
throw new ConfigHandlingException(
String.format("Unable to recreate %s : %s, Existing module instance not found", module, instance),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
ObjectName objectName, ServiceRegistryWrapper services) throws ConfigHandlingException {
try {
ta.reCreateModule(objectName);
- } catch(InstanceNotFoundException e) {
+ } catch (InstanceNotFoundException e) {
throw new ConfigHandlingException(String.format("Unable to recreate instance for %s", objectName),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
- throw new ConfigHandlingException(
- String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
- module,
- instance),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
+ String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
+ throw new ConfigHandlingException(String.format(
+ "Unable to handle missing instance, no missing instances should appear"
+ + " at this point, missing: %s : %s ",
+ module, instance), DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
+ @SuppressWarnings("IllegalCatch")
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
+ ServiceRegistryWrapper services) throws ConfigHandlingException {
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
try {
AttributeConfigElement ace = configAttributeEntry.getValue();
if (!ace.getResolvedValue().isPresent()) {
Object value = ace.getResolvedDefaultValue();
ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
- LOG.debug("Attribute {} set to default value {} for {}", configAttributeEntry.getKey(), value,
- on);
+ LOG.debug("Attribute {} set to default value {} for {}", configAttributeEntry.getKey(), value, on);
} else {
Object value = ace.getResolvedValue().get();
ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
LOG.debug("Attribute {} set to value {} for {}", configAttributeEntry.getKey(), value, on);
}
-
- } catch (Exception e) {
+ } catch (RuntimeException e) {
throw new IllegalStateException("Unable to set attributes for " + on + ", Error with attribute "
+ configAttributeEntry.getKey() + ":" + configAttributeEntry.getValue(), e);
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
+
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
+
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
}
@Override
+ @SuppressWarnings("IllegalCatch")
public synchronized void close() {
for (ObjectName tx : allOpenedTransactions) {
try {
if (isStillOpenTransaction(tx)) {
configRegistryClient.getConfigTransactionClient(tx).abortConfig();
}
- } catch (final Exception e) {
+ } catch (final RuntimeException e) {
LOG.debug("Ignoring exception while closing transaction {}", tx, e);
}
}
public synchronized Optional<ObjectName> getTransaction() {
- if (candidateTx == null){
+ if (candidateTx == null) {
return Optional.absent();
}
public synchronized Optional<ObjectName> getReadTransaction() {
- if (readTx == null){
+ if (readTx == null) {
return Optional.absent();
}
}
/**
- * Used for editConfig test option
+ * Used for editConfig test option.
*/
public synchronized ObjectName getTestTransaction() {
ObjectName testTx = configRegistryClient.beginConfig();
}
/**
- * Commit and notification send must be atomic
+ * Commit and notification send must be atomic.
*/
public CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException {
return commitTransaction(configRegistryClient);
}
/**
- * Commit and notification send must be atomic
- * @param configRegistryClient
+ * Commit and notification send must be atomic.
*/
- public synchronized CommitStatus commitTransaction(final ConfigRegistryClient configRegistryClient) throws ValidationException, ConflictingVersionException {
- if (!getTransaction().isPresent()){
- //making empty commit without prior opened transaction, just return commit status with empty lists
+ public synchronized CommitStatus commitTransaction(final ConfigRegistryClient configRegistryClient)
+ throws ValidationException, ConflictingVersionException {
+ if (!getTransaction().isPresent()) {
+ // making empty commit without prior opened transaction, just return commit
+ // status with empty lists
LOG.debug("Making commit without open candidate transaction for session {}", sessionIdForReporting);
- return new CommitStatus(Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
+ return new CommitStatus(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
}
final Optional<ObjectName> maybeTaON = getTransaction();
ObjectName taON = maybeTaON.get();
}
/**
- * Wiping means removing all module instances keeping the transaction open + service references.
+ * Wiping means removing all module instances keeping the transaction open +
+ * service references.
*/
synchronized void wipeInternal(final ObjectName taON, final boolean isTest) {
ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON);
Set<ObjectName> lookupConfigBeans = transactionClient.lookupConfigBeans();
- int i = lookupConfigBeans.size();
+ int index = lookupConfigBeans.size();
for (ObjectName instance : lookupConfigBeans) {
try {
transactionClient.destroyModule(instance);
} catch (final InstanceNotFoundException e) {
- if (isTest){
+ if (isTest) {
LOG.debug("Unable to clean configuration in transactiom {}", taON, e);
} else {
LOG.warn("Unable to clean configuration in transactiom {}", taON, e);
throw new IllegalStateException("Unable to clean configuration in transactiom " + taON, e);
}
}
- LOG.debug("Transaction {} wiped clean of {} config beans", taON, i);
+ LOG.debug("Transaction {} wiped clean of {} config beans", taON, index);
transactionClient.removeAllServiceReferences();
LOG.debug("Transaction {} wiped clean of all service references", taON);
Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
wipeInternal(taON.get(), false);
}
-
}
public final class Util {
+ private Util() {
+ }
+
public static String writeDate(final Date date) {
return getRevisionFormat().format(date);
}
- public static Date readDate(final String s) throws ParseException {
- return getRevisionFormat().parse(s);
+ public static Date readDate(final String string) throws ParseException {
+ return getRevisionFormat().parse(string);
}
public static void checkType(final Object value, final Class<?> clazz) {
- Preconditions.checkArgument(clazz.isAssignableFrom(value.getClass()), "Unexpected type " + value.getClass()
- + " should be " + clazz + " of " + value);
+ Preconditions.checkArgument(clazz.isAssignableFrom(value.getClass()),
+ "Unexpected type " + value.getClass() + " should be " + clazz + " of " + value);
}
-
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
final Date rev = new Date();
identityMapping.put("namespace", Collections.singletonMap(rev, value));
identityMapping.put("inner", Collections.singletonMap(rev, value));
- final SimpleIdentityRefAttributeReadingStrategy key = new SimpleIdentityRefAttributeReadingStrategy(null, "key", identityMapping);
+ final SimpleIdentityRefAttributeReadingStrategy key = new SimpleIdentityRefAttributeReadingStrategy(null, "key",
+ identityMapping);
String read = key.readElementContent(XmlElement.fromString("<el xmlns=\"namespace\">local</el>"));
- assertEquals(org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(), read);
+ assertEquals(
+ org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(),
+ read);
read = key.readElementContent(XmlElement.fromString("<el xmlns:a=\"inner\" xmlns=\"namespace\">a:local</el>"));
- assertEquals(org.opendaylight.yangtools.yang.common.QName.create(URI.create("inner"), rev, "local").toString(), read);
-
- read = key.readElementContent(XmlElement.fromString("<top xmlns=\"namespace\"><el>local</el></top>").getOnlyChildElement());
- assertEquals(org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(), read);
+ assertEquals(org.opendaylight.yangtools.yang.common.QName.create(URI.create("inner"), rev, "local").toString(),
+ read);
+
+ read = key.readElementContent(
+ XmlElement.fromString("<top xmlns=\"namespace\"><el>local</el></top>").getOnlyChildElement());
+ assertEquals(
+ org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(),
+ read);
}
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
public Map<String, String> additional;
@Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
+ @SuppressWarnings("linelength")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
+ return Arrays.asList(new Object[][] {
// With namespaces
- {"/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
- new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))},
- {"/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
- null},
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
+ new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1")) },
+ { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']", null },
// Without namespaces
- {"/modules/module[name=instanceName][type=moduleType]", null},
- {"/modules/module[type=moduleType][name='instanceName']", null},
- {"/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
- {"/modules/module[type=moduleType and name=instanceName]", null},
- {"/modules/module[name=\"instanceName\" and type=moduleType]", null},
- {"/modules/module[type=\"moduleType\" and name=instanceName]", null},
- {"/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
+ { "/modules/module[name=instanceName][type=moduleType]", null },
+ { "/modules/module[type=moduleType][name='instanceName']", null },
+ { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null },
+ { "/modules/module[type=moduleType and name=instanceName]", null },
+ { "/modules/module[name=\"instanceName\" and type=moduleType]", null },
+ { "/modules/module[type=\"moduleType\" and name=instanceName]", null },
+ { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null },
// With inner beans
- {"/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
- {"/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
- {"/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
- {"/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]",
+ Collections.singletonMap("inner", "b") },
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]",
+ Collections.singletonMap("inner", "b") },
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']",
+ Collections.singletonMap("inner", "b") },
+ { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]",
+ Collections.singletonMap("inner", "b") },
- {"/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
- new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b"))
- },
- });
+ { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
+ new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b")) }, });
}
@Test