From: Ed Warnicke Date: Thu, 3 Jul 2014 21:00:18 +0000 (+0000) Subject: Merge "Complete implementation of DataChangeListenerProxy" X-Git-Tag: release/helium~546 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=05861a85bc830af3fce638c301949da23c803ee4;hp=744726a5d58c50102bb391dc9e4f9bd8defb691a Merge "Complete implementation of DataChangeListenerProxy" --- diff --git a/opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java b/opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java index fef2c71969..a62bd7da06 100644 --- a/opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java +++ b/opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java @@ -8,9 +8,11 @@ package org.opendaylight.protocol.framework; import com.google.common.base.Preconditions; + import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; +import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; @@ -25,9 +27,11 @@ import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; + import java.io.Closeable; import java.net.InetSocketAddress; import java.net.SocketAddress; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,8 +98,8 @@ public abstract class AbstractDispatcher, L extends * * @return ChannelFuture representing the binding process */ - protected ChannelFuture createServer(SocketAddress address, Class channelClass, - final ChannelPipelineInitializer initializer) { + protected ChannelFuture createServer(final SocketAddress address, final Class channelClass, + final ChannelPipelineInitializer initializer) { final ServerBootstrap b = new ServerBootstrap(); b.childHandler(new ChannelInitializer() { @@ -110,6 +114,7 @@ public abstract class AbstractDispatcher, L extends // makes no sense for LocalServer and produces warning b.childOption(ChannelOption.SO_KEEPALIVE, true); } + b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); customizeBootstrap(b); if (b.group() == null) { @@ -151,9 +156,8 @@ public abstract class AbstractDispatcher, L extends protected Future createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer initializer) { final Bootstrap b = new Bootstrap(); final ProtocolSessionPromise p = new ProtocolSessionPromise(executor, address, strategy, b); - b.group(this.workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler( + b.option(ChannelOption.SO_KEEPALIVE, true).handler( new ChannelInitializer() { - @Override protected void initChannel(final SocketChannel ch) { initializer.initializeChannel(ch, p); @@ -162,6 +166,18 @@ public abstract class AbstractDispatcher, L extends customizeBootstrap(b); + if (b.group() == null) { + b.group(workerGroup); + } + + // There is no way to detect if this was already set by + // customizeBootstrap() + try { + b.channel(NioSocketChannel.class); + } catch (IllegalStateException e) { + LOG.trace("Not overriding channelFactory on bootstrap {}", b, e); + } + p.connect(); LOG.debug("Client created."); return p; diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBean.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java similarity index 87% rename from opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBean.java rename to opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java index 759541dc26..7ecf758bda 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBean.java +++ b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java @@ -5,7 +5,7 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ -package org.opendaylight.controller.config.manager.impl.jmx; +package org.opendaylight.controller.config.api.jmx; import javax.management.ObjectName; diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java index dedeeed789..ba6676b927 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.config.manager.impl.jmx; import javax.management.ObjectName; +import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean; public class ServiceReferenceMXBeanImpl implements ServiceReferenceMXBean { private ObjectName currentImplementation; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java index 3e7b65e1bd..8c132c93b2 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java @@ -13,7 +13,7 @@ import org.junit.Test; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; import org.opendaylight.controller.config.manager.impl.AbstractConfigTest.RecordingBundleContextServiceRegistrationHandler.RegistrationHolder; import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; -import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceMXBean; +import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean; import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory; import org.opendaylight.controller.config.manager.testingservices.parallelapsp.test.AbstractParallelAPSPTest; import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory; diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java index 549ff9ffcf..559993f264 100644 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java +++ b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java @@ -26,6 +26,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; +import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean; public class ConfigRegistryJMXClient implements ConfigRegistryClient { private final ConfigRegistryMXBean configRegistryMXBeanProxy; @@ -65,10 +66,27 @@ public class ConfigRegistryJMXClient implements ConfigRegistryClient { configMBeanServer); } + /** + * Usage of this method indicates error as config JMX uses solely MXBeans. + * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)} + * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)} + * This method will be removed soon. + */ + @Deprecated public T newMBeanProxy(ObjectName on, Class clazz) { + on = translateServiceRefIfPossible(on, clazz, configMBeanServer); return JMX.newMBeanProxy(configMBeanServer, on, clazz); } + static ObjectName translateServiceRefIfPossible(ObjectName on, Class clazz, MBeanServer configMBeanServer) { + if (ObjectNameUtil.isServiceReference(on) && clazz.equals(ServiceReferenceMXBean.class) == false) { + ServiceReferenceMXBean proxy = JMX.newMXBeanProxy(configMBeanServer, on, ServiceReferenceMXBean.class); + on = proxy.getCurrentImplementation(); + } + return on; + } + + public T newMXBeanProxy(ObjectName on, Class clazz) { return JMX.newMXBeanProxy(configMBeanServer, on, clazz); } @@ -211,5 +229,4 @@ public class ConfigRegistryJMXClient implements ConfigRegistryClient { public void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException { configRegistryMXBeanProxy.checkServiceReferenceExists(objectName); } - } diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java index 4adc0d9364..4cf766a812 100644 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java +++ b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java @@ -7,13 +7,8 @@ */ package org.opendaylight.controller.config.util; -import org.opendaylight.controller.config.api.ConflictingVersionException; -import org.opendaylight.controller.config.api.ValidationException; -import org.opendaylight.controller.config.api.jmx.CommitStatus; -import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean; -import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean; -import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; - +import java.util.Map; +import java.util.Set; import javax.management.Attribute; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; @@ -22,8 +17,12 @@ import javax.management.JMX; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.ObjectName; -import java.util.Map; -import java.util.Set; +import org.opendaylight.controller.config.api.ConflictingVersionException; +import org.opendaylight.controller.config.api.ValidationException; +import org.opendaylight.controller.config.api.jmx.CommitStatus; +import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean; +import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean; +import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; public class ConfigTransactionJMXClient implements ConfigTransactionClient { private final ConfigRegistryMXBean configRegistryMXBeanProxy; @@ -44,9 +43,21 @@ public class ConfigTransactionJMXClient implements ConfigTransactionClient { } public T newMXBeanProxy(ObjectName on, Class clazz) { + // if on is without transaction, add it. Reason is that when using getters on MXBeans the transaction name is stripped + on = ObjectNameUtil.withTransactionName(on, getTransactionName()); + // if this is service reference and user requests for implementation, look it up + on = ConfigRegistryJMXClient.translateServiceRefIfPossible(on, clazz, configMBeanServer); + on = ObjectNameUtil.withTransactionName(on, getTransactionName()); return JMX.newMXBeanProxy(configMBeanServer, on, clazz); } + /** + * Usage of this method indicates error as config JMX uses solely MXBeans. + * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)} + * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)} + * This method will be removed soon. + */ + @Deprecated public T newMBeanProxy(ObjectName on, Class clazz) { return JMX.newMBeanProxy(configMBeanServer, on, clazz); } diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java index ae06400195..775fa9fc20 100644 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java +++ b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java @@ -7,11 +7,6 @@ */ package org.opendaylight.controller.config.yangjmxgenerator; -import java.net.URI; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - import org.opendaylight.yangtools.yang.common.QName; public class ConfigConstants { @@ -33,33 +28,14 @@ public class ConfigConstants { public static final QName RPC_CONTEXT_REF_GROUPING_LEAF = createRpcXQName("context-instance"); public static final QName RPC_CONTEXT_INSTANCE_EXTENSION_QNAME = createRpcXQName("rpc-context-instance"); - public static QName createConfigQName(String localName) { - return createQName(CONFIG_NAMESPACE, "2013-04-05", localName); + public static QName createConfigQName(final String localName) { + // FIXME: pre-construct QNameModule + return QName.create(CONFIG_NAMESPACE, "2013-04-05", localName); } - public static QName createRpcXQName(String localName) { - return createQName("urn:ietf:params:xml:ns:yang:rpc-context", + public static QName createRpcXQName(final String localName) { + // FIXME: pre-construct QNameModule + return QName.create("urn:ietf:params:xml:ns:yang:rpc-context", "2013-06-17", localName); } - - /** - * - * @param uri - * @param revisionDate - * in format yyyy-MM-dd - * @param localName - * @return - */ - private static QName createQName(String uri, String revisionDate, - String localName) { - SimpleDateFormat revisionFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date revision; - try { - revision = revisionFormat.parse(revisionDate); - } catch (ParseException e) { - throw new RuntimeException(e); - } - return new QName(URI.create(uri), revision, localName); - } - } diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java index 89f3a4a519..d8c5a56fb7 100644 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java +++ b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java @@ -18,6 +18,7 @@ import com.google.common.base.Optional; import com.google.common.collect.Collections2; import com.google.common.collect.Maps; import com.google.common.collect.Sets; + import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -26,7 +27,9 @@ import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; + import javax.annotation.Nullable; + import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute; import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc; import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute; @@ -64,27 +67,27 @@ final class ModuleMXBeanEntryBuilder { private TypeProviderWrapper typeProviderWrapper; private String packageName; - public ModuleMXBeanEntryBuilder setModule(Module module) { + public ModuleMXBeanEntryBuilder setModule(final Module module) { this.currentModule = module; return this; } - public ModuleMXBeanEntryBuilder setqNamesToSIEs(Map qNamesToSIEs) { + public ModuleMXBeanEntryBuilder setqNamesToSIEs(final Map qNamesToSIEs) { this.qNamesToSIEs = qNamesToSIEs; return this; } - public ModuleMXBeanEntryBuilder setSchemaContext(SchemaContext schemaContext) { + public ModuleMXBeanEntryBuilder setSchemaContext(final SchemaContext schemaContext) { this.schemaContext = schemaContext; return this; } - public ModuleMXBeanEntryBuilder setTypeProviderWrapper(TypeProviderWrapper typeProviderWrapper) { + public ModuleMXBeanEntryBuilder setTypeProviderWrapper(final TypeProviderWrapper typeProviderWrapper) { this.typeProviderWrapper = typeProviderWrapper; return this; } - public ModuleMXBeanEntryBuilder setPackageName(String packageName) { + public ModuleMXBeanEntryBuilder setPackageName(final String packageName) { this.packageName = packageName; return this; } @@ -147,7 +150,7 @@ final class ModuleMXBeanEntryBuilder { return result; } - private static void cleanUpNulls(Map result) { + private static void cleanUpNulls(final Map result) { for (Map.Entry entry : result.entrySet()) { ModuleMXBeanEntry module = entry.getValue(); if (module.getAttributes() == null) { @@ -160,14 +163,14 @@ final class ModuleMXBeanEntryBuilder { } } - private static void checkUnaugumentedIdentities(Map unaugmentedModuleIdentities) { + private static void checkUnaugumentedIdentities(final Map unaugmentedModuleIdentities) { if (unaugmentedModuleIdentities.size() > 0) { logger.warn("Augmentation not found for all currentModule identities: {}", unaugmentedModuleIdentities.keySet()); } } - private static void checkAttributeNamesUniqueness(Map uniqueGeneratedClassesNames, Map result) { + private static void checkAttributeNamesUniqueness(final Map uniqueGeneratedClassesNames, final Map result) { for (Map.Entry entry : result.entrySet()) { checkUniqueRuntimeBeanAttributesName(entry.getValue(), uniqueGeneratedClassesNames); @@ -212,29 +215,30 @@ final class ModuleMXBeanEntryBuilder { return moduleIdentities; } - private Collection castChildNodesToChoiceCases(Set childNodes) { + private Collection castChildNodesToChoiceCases(final Set childNodes) { return Collections2.transform(childNodes, new Function() { @Nullable @Override - public ChoiceCaseNode apply(@Nullable DataSchemaNode input) { + public ChoiceCaseNode apply(@Nullable final DataSchemaNode input) { return (ChoiceCaseNode) input; } }); } - private boolean areAllChildrenChoiceCaseNodes(Set childNodes) { + private boolean areAllChildrenChoiceCaseNodes(final Set childNodes) { for (DataSchemaNode childNode : childNodes) { - if (childNode instanceof ChoiceCaseNode == false) + if (childNode instanceof ChoiceCaseNode == false) { return false; + } } return true; } - private void processChoiceCaseNode(Map result, - Map uniqueGeneratedClassesNames, String configModulePrefix, - Map moduleIdentities, - Map unaugmentedModuleIdentities, AugmentationSchema augmentation, - DataSchemaNode when) { + private void processChoiceCaseNode(final Map result, + final Map uniqueGeneratedClassesNames, final String configModulePrefix, + final Map moduleIdentities, + final Map unaugmentedModuleIdentities, final AugmentationSchema augmentation, + final DataSchemaNode when) { ChoiceCaseNode choiceCaseNode = (ChoiceCaseNode) when; if (choiceCaseNode.getConstraints() == null || choiceCaseNode.getConstraints().getWhenCondition() == null) { @@ -301,12 +305,12 @@ final class ModuleMXBeanEntryBuilder { } checkState(Objects.equals(nullableDummyContainerName, moduleMXBeanEntry.getNullableDummyContainerName()), "Mismatch in module " + moduleMXBeanEntry.toString() + " - dummy container must be present/missing in" + - " both state and configuration"); + " both state and configuration"); } else { ModuleMXBeanEntry.ModuleMXBeanEntryInitial initial = new ModuleMXBeanEntry.ModuleMXBeanEntryInitialBuilder() - .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix) - .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule)) - .build(); + .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix) + .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule)) + .build(); // construct ModuleMXBeanEntry ModuleMXBeanEntry moduleMXBeanEntry = new ModuleMXBeanEntry(initial, yangToAttributes, providedServices, @@ -319,8 +323,8 @@ final class ModuleMXBeanEntryBuilder { } } - private void checkUniqueRuntimeBeansGeneratedClasses(Map uniqueGeneratedClassesNames, - DataSchemaNode when, Collection runtimeBeans) { + private void checkUniqueRuntimeBeansGeneratedClasses(final Map uniqueGeneratedClassesNames, + final DataSchemaNode when, final Collection runtimeBeans) { for (RuntimeBeanEntry runtimeBean : runtimeBeans) { final String javaNameOfRuntimeMXBean = runtimeBean.getJavaNameOfRuntimeMXBean(); if (uniqueGeneratedClassesNames.containsKey(javaNameOfRuntimeMXBean)) { @@ -331,8 +335,8 @@ final class ModuleMXBeanEntryBuilder { } } - private static void checkUniqueRuntimeBeanAttributesName(ModuleMXBeanEntry mxBeanEntry, - Map uniqueGeneratedClassesNames) { + private static void checkUniqueRuntimeBeanAttributesName(final ModuleMXBeanEntry mxBeanEntry, + final Map uniqueGeneratedClassesNames) { for (RuntimeBeanEntry runtimeBeanEntry : mxBeanEntry.getRuntimeBeans()) { for (String runtimeAttName : runtimeBeanEntry.getYangPropertiesToTypesMap().keySet()) { if (mxBeanEntry.getAttributes().keySet().contains(runtimeAttName)) { @@ -344,8 +348,8 @@ final class ModuleMXBeanEntryBuilder { } } - private void checkUniqueAttributesWithGeneratedClass(Map uniqueGeneratedClassNames, - QName parentQName, Map yangToAttributes) { + private void checkUniqueAttributesWithGeneratedClass(final Map uniqueGeneratedClassNames, + final QName parentQName, final Map yangToAttributes) { for (Map.Entry attr : yangToAttributes.entrySet()) { if (attr.getValue() instanceof TOAttribute) { checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName, (TOAttribute) attr.getValue()); @@ -357,7 +361,7 @@ final class ModuleMXBeanEntryBuilder { } } - private void checkUniqueTOAttr(Map uniqueGeneratedClassNames, QName parentQName, TOAttribute attr) { + private void checkUniqueTOAttr(final Map uniqueGeneratedClassNames, final QName parentQName, final TOAttribute attr) { final String upperCaseCamelCase = attr.getUpperCaseCammelCase(); if (uniqueGeneratedClassNames.containsKey(upperCaseCamelCase)) { QName firstDefinedQName = uniqueGeneratedClassNames.get(upperCaseCamelCase); @@ -367,9 +371,9 @@ final class ModuleMXBeanEntryBuilder { } } - private Collection fillRuntimeBeans(DataNodeContainer dataNodeContainer, Module currentModule, - TypeProviderWrapper typeProviderWrapper, String packageName, String moduleLocalNameFromXPath, - String javaNamePrefix) { + private Collection fillRuntimeBeans(final DataNodeContainer dataNodeContainer, final Module currentModule, + final TypeProviderWrapper typeProviderWrapper, final String packageName, final String moduleLocalNameFromXPath, + final String javaNamePrefix) { return RuntimeBeanEntry.extractClassNameToRuntimeBeanMap(packageName, dataNodeContainer, moduleLocalNameFromXPath, typeProviderWrapper, javaNamePrefix, currentModule).values(); @@ -383,7 +387,7 @@ final class ModuleMXBeanEntryBuilder { * @param choiceCaseNode state or configuration case statement * @return either choiceCaseNode or its only child container */ - private HAS_CHILDREN_AND_QNAME getDataNodeContainer(ChoiceCaseNode choiceCaseNode) { + private HAS_CHILDREN_AND_QNAME getDataNodeContainer(final ChoiceCaseNode choiceCaseNode) { Set childNodes = choiceCaseNode.getChildNodes(); if (childNodes.size() == 1) { DataSchemaNode onlyChild = childNodes.iterator().next(); @@ -398,9 +402,9 @@ final class ModuleMXBeanEntryBuilder { return (HAS_CHILDREN_AND_QNAME) choiceCaseNode; } - private Map fillConfiguration(DataNodeContainer dataNodeContainer, Module currentModule, - TypeProviderWrapper typeProviderWrapper, Map qNamesToSIEs, - SchemaContext schemaContext, String packageName) { + private Map fillConfiguration(final DataNodeContainer dataNodeContainer, final Module currentModule, + final TypeProviderWrapper typeProviderWrapper, final Map qNamesToSIEs, + final SchemaContext schemaContext, final String packageName) { Map yangToAttributes = new HashMap<>(); Set childNodes = dataNodeContainer.getChildNodes(); for (DataSchemaNode attrNode : childNodes) { @@ -411,8 +415,8 @@ final class ModuleMXBeanEntryBuilder { return yangToAttributes; } - private Map findProvidedServices(IdentitySchemaNode moduleIdentity, Module currentModule, - Map qNamesToSIEs, SchemaContext schemaContext) { + private Map findProvidedServices(final IdentitySchemaNode moduleIdentity, final Module currentModule, + final Map qNamesToSIEs, final SchemaContext schemaContext) { Map result = new HashMap<>(); for (UnknownSchemaNode unknownNode : moduleIdentity.getUnknownSchemaNodes()) { if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) { @@ -425,9 +429,9 @@ final class ModuleMXBeanEntryBuilder { return result; } - private AttributeIfc getAttributeValue(DataSchemaNode attrNode, Module currentModule, - Map qNamesToSIEs, TypeProviderWrapper typeProviderWrapper, - SchemaContext schemaContext, String packageName) { + private AttributeIfc getAttributeValue(final DataSchemaNode attrNode, final Module currentModule, + final Map qNamesToSIEs, final TypeProviderWrapper typeProviderWrapper, + final SchemaContext schemaContext, final String packageName) { if (attrNode instanceof LeafSchemaNode) { // simple type @@ -460,9 +464,9 @@ final class ModuleMXBeanEntryBuilder { } } - private Optional extractDependency(DataNodeContainer dataNodeContainer, - DataSchemaNode attrNode, Module currentModule, Map qNamesToSIEs, - SchemaContext schemaContext) { + private Optional extractDependency(final DataNodeContainer dataNodeContainer, + final DataSchemaNode attrNode, final Module currentModule, final Map qNamesToSIEs, + final SchemaContext schemaContext) { if (dataNodeContainer.getUses().size() == 1 && getChildNodeSizeWithoutUses(dataNodeContainer) == 0) { // reference UsesNode usesNode = dataNodeContainer.getUses().iterator().next(); @@ -490,7 +494,7 @@ final class ModuleMXBeanEntryBuilder { return Optional.absent(); } - private int getChildNodeSizeWithoutUses(DataNodeContainer csn) { + private int getChildNodeSizeWithoutUses(final DataNodeContainer csn) { int result = 0; for (DataSchemaNode dsn : csn.getChildNodes()) { if (dsn.isAddedByUses() == false) { @@ -500,8 +504,8 @@ final class ModuleMXBeanEntryBuilder { return result; } - private ServiceInterfaceEntry findSIE(String prefixAndIdentityLocalName, Module currentModule, - Map qNamesToSIEs, SchemaContext schemaContext) { + private ServiceInterfaceEntry findSIE(final String prefixAndIdentityLocalName, final Module currentModule, + final Map qNamesToSIEs, final SchemaContext schemaContext) { Matcher m = PREFIX_COLON_LOCAL_NAME.matcher(prefixAndIdentityLocalName); Module foundModule; @@ -518,13 +522,13 @@ final class ModuleMXBeanEntryBuilder { foundModule = currentModule; // no prefix => SIE is in currentModule localSIName = prefixAndIdentityLocalName; } - QName siQName = new QName(foundModule.getNamespace(), foundModule.getRevision(), localSIName); + QName siQName = QName.create(foundModule.getNamespace(), foundModule.getRevision(), localSIName); ServiceInterfaceEntry sie = qNamesToSIEs.get(siQName); checkState(sie != null, "Cannot find referenced Service Interface by " + prefixAndIdentityLocalName); return sie; } - private ModuleImport findModuleImport(Module module, String prefix) { + private ModuleImport findModuleImport(final Module module, final String prefix) { for (ModuleImport moduleImport : module.getImports()) { if (moduleImport.getPrefix().equals(prefix)) { return moduleImport; @@ -534,13 +538,13 @@ final class ModuleMXBeanEntryBuilder { } @VisibleForTesting - static Matcher getWhenConditionMatcher(String prefix, RevisionAwareXPath whenConstraint) { + static Matcher getWhenConditionMatcher(final String prefix, final RevisionAwareXPath whenConstraint) { String xpathRegex = MODULE_CONDITION_XPATH_TEMPLATE.replace(MAGIC_STRING, prefix); Pattern pattern = Pattern.compile(xpathRegex); return pattern.matcher(whenConstraint.toString()); } - String getConfigModulePrefixFromImport(Module currentModule) { + String getConfigModulePrefixFromImport(final Module currentModule) { for (ModuleImport currentImport : currentModule.getImports()) { if (currentImport.getModuleName().equals(ConfigConstants.CONFIG_MODULE)) { return currentImport.getPrefix(); diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java index 5fea8fd078..ccd701d1fb 100644 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java +++ b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java @@ -12,7 +12,7 @@ import org.opendaylight.yangtools.yang.model.api.Module; public class ModuleUtil { - public static QName getQName(Module currentModule){ - return new QName(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName()); + public static QName getQName(final Module currentModule) { + return QName.create(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName()); } } diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java index c941d1504d..23b071c817 100644 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java +++ b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java @@ -13,6 +13,7 @@ import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.collect.Lists; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -25,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; + import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc; import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute; import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute; @@ -65,11 +67,11 @@ public class RuntimeBeanEntry { private final Set rpcs; @VisibleForTesting - RuntimeBeanEntry(String packageName, - DataNodeContainer nodeForReporting, String yangName, - String javaNamePrefix, boolean isRoot, - Optional keyYangName, List attributes, - List children, Set rpcs) { + RuntimeBeanEntry(final String packageName, + final DataNodeContainer nodeForReporting, final String yangName, + final String javaNamePrefix, final boolean isRoot, + final Optional keyYangName, final List attributes, + final List children, final Set rpcs) { checkArgument(isRoot == false || keyYangName.isPresent() == false, "Root RuntimeBeanEntry must not have key " + "set"); @@ -86,7 +88,7 @@ public class RuntimeBeanEntry { for (AttributeIfc a : attributes) { checkState(map.containsKey(a.getAttributeYangName()) == false, "Attribute already defined: " + a.getAttributeYangName() - + " in " + nodeForReporting); + + " in " + nodeForReporting); map.put(a.getAttributeYangName(), a); } @@ -110,9 +112,9 @@ public class RuntimeBeanEntry { * not contain special configuration for it. */ public static Map extractClassNameToRuntimeBeanMap( - String packageName, DataNodeContainer container, - String moduleYangName, TypeProviderWrapper typeProviderWrapper, - String javaNamePrefix, Module currentModule) { + final String packageName, final DataNodeContainer container, + final String moduleYangName, final TypeProviderWrapper typeProviderWrapper, + final String javaNamePrefix, final Module currentModule) { Map> identitiesToRpcs = getIdentitiesToRpcs(currentModule); @@ -151,7 +153,7 @@ public class RuntimeBeanEntry { } private static Map> getIdentitiesToRpcs( - Module currentModule) { + final Module currentModule) { // currently only looks for local identities (found in currentModule) Map> result = new HashMap<>(); for (IdentitySchemaNode identity : currentModule.getIdentities()) { @@ -164,14 +166,16 @@ public class RuntimeBeanEntry { if (input != null) { for (UsesNode uses : input.getUses()) { - if (uses.getGroupingPath().getPath().size() != 1) + if (uses.getGroupingPath().getPath().size() != 1) { continue; + } // check grouping path QName qname = uses.getGroupingPath().getPath().get(0); if (false == qname - .equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) + .equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) { continue; + } for (SchemaNode refinedNode : uses.getRefines().values()) { @@ -181,7 +185,7 @@ public class RuntimeBeanEntry { .equals(unknownSchemaNode.getNodeType())) { String localIdentityName = unknownSchemaNode .getNodeParameter(); - QName identityQName = new QName( + QName identityQName = QName.create( currentModule.getNamespace(), currentModule.getRevision(), localIdentityName); @@ -208,9 +212,9 @@ public class RuntimeBeanEntry { * in subtree. */ private static AttributesRpcsAndRuntimeBeans extractSubtree( - String packageName, DataNodeContainer subtree, - TypeProviderWrapper typeProviderWrapper, Module currentModule, - Map> identitiesToRpcs) { + final String packageName, final DataNodeContainer subtree, + final TypeProviderWrapper typeProviderWrapper, final Module currentModule, + final Map> identitiesToRpcs) { List attributes = Lists.newArrayList(); // List javaAttributes = new ArrayList<>(); @@ -258,7 +262,7 @@ public class RuntimeBeanEntry { if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME .equals(unknownSchemaNode.getNodeType())) { String localIdentityName = unknownSchemaNode.getNodeParameter(); - QName identityQName = new QName(currentModule.getNamespace(), + QName identityQName = QName.create(currentModule.getNamespace(), currentModule.getRevision(), localIdentityName); Set rpcDefinitions = identitiesToRpcs .get(identityQName); @@ -290,8 +294,8 @@ public class RuntimeBeanEntry { for (DataSchemaNode childNode : sortAttributes(rpcDefinition.getInput() .getChildNodes())) { if (childNode.isAddedByUses() == false) { // skip - // refined - // context-instance + // refined + // context-instance checkArgument(childNode instanceof LeafSchemaNode, "Unexpected type of rpc input type. " + "Currently only leafs and empty output nodes are supported, got " + childNode); JavaAttribute javaAttribute = new JavaAttribute( @@ -310,8 +314,8 @@ public class RuntimeBeanEntry { attributes, rpcs); } - private static AttributeIfc getReturnTypeAttribute(DataSchemaNode child, TypeProviderWrapper typeProviderWrapper, - String packageName) { + private static AttributeIfc getReturnTypeAttribute(final DataSchemaNode child, final TypeProviderWrapper typeProviderWrapper, + final String packageName) { if (child instanceof LeafSchemaNode) { LeafSchemaNode leaf = (LeafSchemaNode) child; return new JavaAttribute(leaf, typeProviderWrapper); @@ -328,10 +332,10 @@ public class RuntimeBeanEntry { } } - private static Collection sortAttributes(Set childNodes) { + private static Collection sortAttributes(final Set childNodes) { final TreeSet dataSchemaNodes = new TreeSet<>(new Comparator() { @Override - public int compare(DataSchemaNode o1, DataSchemaNode o2) { + public int compare(final DataSchemaNode o1, final DataSchemaNode o2) { return o1.getQName().getLocalName().compareTo(o2.getQName().getLocalName()); } }); @@ -339,20 +343,21 @@ public class RuntimeBeanEntry { return dataSchemaNodes; } - private static boolean isInnerStateBean(DataSchemaNode child) { + private static boolean isInnerStateBean(final DataSchemaNode child) { for (UnknownSchemaNode unknownSchemaNode : child .getUnknownSchemaNodes()) { if (unknownSchemaNode.getNodeType().equals( - ConfigConstants.INNER_STATE_BEAN_EXTENSION_QNAME)) + ConfigConstants.INNER_STATE_BEAN_EXTENSION_QNAME)) { return true; + } } return false; } - private static RuntimeBeanEntry createHierarchical(String packageName, - ListSchemaNode listSchemaNode, - TypeProviderWrapper typeProviderWrapper, Module currentModule, - Map> identitiesToRpcs) { + private static RuntimeBeanEntry createHierarchical(final String packageName, + final ListSchemaNode listSchemaNode, + final TypeProviderWrapper typeProviderWrapper, final Module currentModule, + final Map> identitiesToRpcs) { // supported are numeric types, strings, enums // get all attributes @@ -387,10 +392,10 @@ public class RuntimeBeanEntry { return rbFromAttributes; } - private static RuntimeBeanEntry createRoot(String packageName, - DataNodeContainer nodeForReporting, String attributeYangName, - List attributes, String javaNamePrefix, - List children, Set rpcs) { + private static RuntimeBeanEntry createRoot(final String packageName, + final DataNodeContainer nodeForReporting, final String attributeYangName, + final List attributes, final String javaNamePrefix, + final List children, final Set rpcs) { return new RuntimeBeanEntry(packageName, nodeForReporting, attributeYangName, javaNamePrefix, true, Optional. absent(), attributes, children, rpcs); @@ -442,8 +447,8 @@ public class RuntimeBeanEntry { private final Set rpcs; public AttributesRpcsAndRuntimeBeans( - List runtimeBeanEntries, - List attributes, Set rpcs) { + final List runtimeBeanEntries, + final List attributes, final Set rpcs) { this.runtimeBeanEntries = runtimeBeanEntries; this.attributes = attributes; this.rpcs = rpcs; @@ -472,8 +477,8 @@ public class RuntimeBeanEntry { private final AttributeIfc returnType; private final String yangName; - Rpc(AttributeIfc returnType, String name, String yangName, - List parameters) { + Rpc(final AttributeIfc returnType, final String name, final String yangName, + final List parameters) { this.returnType = returnType; this.name = name; this.parameters = parameters; @@ -503,12 +508,12 @@ public class RuntimeBeanEntry { return getJavaNameOfRuntimeMXBean(javaNamePrefix); } - public String getFullyQualifiedName(String typeName) { + public String getFullyQualifiedName(final String typeName) { return FullyQualifiedNameHelper.getFullyQualifiedName(packageName, typeName); } - private static String getJavaNameOfRuntimeMXBean(String javaNamePrefix) { + private static String getJavaNameOfRuntimeMXBean(final String javaNamePrefix) { return javaNamePrefix + MXBEAN_SUFFIX; } diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java index dd44246867..fab273c600 100644 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java +++ b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java @@ -7,7 +7,35 @@ */ package org.opendaylight.controller.config.yangjmxgenerator; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + import com.google.common.collect.Sets; + +import java.net.URI; +import java.net.URISyntaxException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; + +import javax.management.openmbean.ArrayType; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.SimpleType; + import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc; @@ -25,32 +53,6 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.SimpleType; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - public class ModuleMXBeanEntryTest extends AbstractYangTest { public static final String PACKAGE_NAME = "pack2"; @@ -95,7 +97,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { PACKAGE_NAME,identitiesToSIs)); Map namesToMBEs = ModuleMXBeanEntry .create(jmxImplModule, modulesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)) - , PACKAGE_NAME); + , PACKAGE_NAME); Map attributes = namesToMBEs.get("impl-netconf") .getAttributes(); @@ -120,7 +122,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { assertThat(threadFactoryAttribute.getType().getName(), is("ObjectName")); } - private void assertCorrectAttributesSize(Map namesToMBEs, Map attributes) { + private void assertCorrectAttributesSize(final Map namesToMBEs, final Map attributes) { assertEquals(14, attributes.size()); assertEquals(1, namesToMBEs.get("impl-netconf").getRuntimeBeans().size()); assertEquals(2, namesToMBEs.get("impl-netconf").getRuntimeBeans().iterator().next().getAttributes().size()); @@ -131,10 +133,11 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { } protected RuntimeBeanEntry findFirstByYangName( - Collection runtimeBeans, String yangName) { + final Collection runtimeBeans, final String yangName) { for (RuntimeBeanEntry rb : runtimeBeans) { - if (yangName.equals(rb.getYangName())) + if (yangName.equals(rb.getYangName())) { return rb; + } } throw new IllegalArgumentException("Yang name not found:" + yangName + " in " + runtimeBeans); @@ -150,7 +153,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { "/config:modules/config:module/config:type=\"threadpool-dynamic\""); } - private void assertMatches(String prefix, String input) { + private void assertMatches(final String prefix, final String input) { RevisionAwareXPath whenConstraint = mock(RevisionAwareXPath.class); doReturn(input).when(whenConstraint).toString(); Matcher output = ModuleMXBeanEntryBuilder.getWhenConditionMatcher(prefix, @@ -181,7 +184,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { is((Type) Types.typeForClass(Long.class))); } // check dependency on thread factory - QName threadfactoryQName = new QName(THREADS_NAMESPACE, + QName threadfactoryQName = QName.create(THREADS_NAMESPACE, THREADS_REVISION_DATE, "threadfactory"); ServiceInterfaceEntry threadFactorySIEntry = modulesToSIEs .get(threadfactoryQName); @@ -192,7 +195,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { DataSchemaNode mockedDataSchemaNode = mock(DataSchemaNode.class); doReturn(Collections.emptyList()).when(mockedDataSchemaNode) - .getUnknownSchemaNodes(); + .getUnknownSchemaNodes(); doReturn(threadfactoryQName).when(mockedDataSchemaNode).getQName(); AttributeIfc expectedDependencyAttribute = new DependencyAttribute( mockedDataSchemaNode, threadFactorySIEntry, @@ -200,7 +203,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest { assertThat(actualThreadFactory, is(expectedDependencyAttribute)); assertThat( dynamicThreadPool - .getFullyQualifiedName("DynamicThreadPoolModuleMXBean"), + .getFullyQualifiedName("DynamicThreadPoolModuleMXBean"), is(PACKAGE_NAME + ".DynamicThreadPoolModuleMXBean")); assertThat(dynamicThreadPool.getNullableDescription(), is("threadpool-dynamic description")); diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java index eed8695103..f22edbf948 100644 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java +++ b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java @@ -7,7 +7,12 @@ */ package org.opendaylight.controller.config.yangjmxgenerator; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + import com.google.common.collect.Sets; + import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; @@ -20,13 +25,11 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; + import org.hamcrest.CoreMatchers; import org.junit.Test; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; public class ServiceInterfaceEntryTest extends AbstractYangTest { public static final String PACKAGE_NAME = "packages.sis"; @@ -53,15 +56,15 @@ public class ServiceInterfaceEntryTest extends AbstractYangTest { } } - public static final QName EVENTBUS_QNAME = new QName(THREADS_NAMESPACE, + public static final QName EVENTBUS_QNAME = QName.create(THREADS_NAMESPACE, THREADS_REVISION_DATE, "eventbus"); - public static final QName THREADFACTORY_QNAME = new QName( + public static final QName THREADFACTORY_QNAME = QName.create( THREADS_NAMESPACE, THREADS_REVISION_DATE, "threadfactory"); - public static final QName THREADPOOL_QNAME = new QName(THREADS_NAMESPACE, + public static final QName THREADPOOL_QNAME = QName.create(THREADS_NAMESPACE, THREADS_REVISION_DATE, "threadpool"); - public static final QName SCHEDULED_THREADPOOL_QNAME = new QName( + public static final QName SCHEDULED_THREADPOOL_QNAME = QName.create( THREADS_NAMESPACE, THREADS_REVISION_DATE, "scheduled-threadpool"); - public static final QName SCHEDULED_EXECUTOR_SERVICE_QNAME = new QName( + public static final QName SCHEDULED_EXECUTOR_SERVICE_QNAME = QName.create( THREADS_NAMESPACE, THREADS_REVISION_DATE, "scheduled-executor-service"); public static final String SCHEDULED_THREADPOOL_INTERFACE_NAME = "ScheduledThreadPoolServiceInterface"; @@ -133,9 +136,10 @@ public class ServiceInterfaceEntryTest extends AbstractYangTest { + SCHEDULED_THREADPOOL_INTERFACE_NAME)); } - static String trimInnerSpacesOrNull(String input) { - if (input == null) + static String trimInnerSpacesOrNull(final String input) { + if (input == null) { return null; + } return input.replaceAll("\\s{2,}", " "); } } diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml index 7b1df98247..afeddbfaab 100644 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml +++ b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml @@ -35,6 +35,10 @@ binding:binding-data-broker binding-data-broker + + binding:binding-async-data-broker + binding-data-broker + diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java index 5959d23366..e2c1386775 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java @@ -7,9 +7,12 @@ */ package org.opendaylight.controller.sal.compatibility; +import com.google.common.collect.Iterables; + import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -733,26 +736,45 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI } private boolean isKnownNodeConnector(final InstanceIdentifier nodeConnectorIdentifier) { - final List path = nodeConnectorIdentifier.getPath(); - if (path.size() >= 3) { - final PathArgument nodePath = path.get(1); - final PathArgument nodeConnectorPath = path.get(2); - final List nodeConnectors = nodeToNodeConnectorsMap.get(nodePath); - if (nodeConnectors != null) { - return nodeConnectors.contains(nodeConnectorPath); - } + final Iterator it = nodeConnectorIdentifier.getPathArguments().iterator(); + + if (!it.hasNext()) { + return false; } - return false; + it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodePath = it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodeConnectorPath = it.next(); + + final List nodeConnectors = nodeToNodeConnectorsMap.get(nodePath); + return nodeConnectors == null ? false : + nodeConnectors.contains(nodeConnectorPath); } private boolean recordNodeConnector(final InstanceIdentifier nodeConnectorIdentifier) { - final List path = nodeConnectorIdentifier.getPath(); - if (path.size() < 3) { + final Iterator it = nodeConnectorIdentifier.getPathArguments().iterator(); + + if (!it.hasNext()) { return false; } + it.next(); - final PathArgument nodePath = path.get(1); - final PathArgument nodeConnectorPath = path.get(2); + if (!it.hasNext()) { + return false; + } + final PathArgument nodePath = it.next(); + + if (!it.hasNext()) { + return false; + } + final PathArgument nodeConnectorPath = it.next(); synchronized (this) { List nodeConnectors = this.nodeToNodeConnectorsMap.get(nodePath); @@ -766,6 +788,6 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI } private List removeNodeConnectors(final InstanceIdentifier nodeIdentifier) { - return this.nodeToNodeConnectorsMap.remove(nodeIdentifier.getPath().get(1)); + return this.nodeToNodeConnectorsMap.remove(Iterables.get(nodeIdentifier.getPathArguments(), 1)); } } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java index 17cd67a857..018e26878c 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java @@ -10,12 +10,10 @@ import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; import org.opendaylight.controller.sal.core.api.Provider; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService; -import org.osgi.framework.BundleContext; public class BindingAsyncDataBrokerImplModule extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModule implements Provider { - private BundleContext bundleContext; public BindingAsyncDataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { @@ -42,25 +40,15 @@ public class BindingAsyncDataBrokerImplModule extends // FIXME: Switch this to DOM Broker registration which would not require // BundleContext when API are updated. - ProviderSession session = domBroker.registerProvider(this, getBundleContext()); + ProviderSession session = domBroker.registerProvider(this, null); DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class); SchemaService schemaService = session.getService(SchemaService.class); return new ForwardedBindingDataBroker(domDataBroker, mappingService, schemaService); } - // FIXME: Remove this when DOM Broker registration would not require - // BundleContext - @Deprecated - private BundleContext getBundleContext() { - return bundleContext; - } - // FIXME: Remove this when DOM Broker registration would not require - // BundleContext - @Deprecated - void setBundleContext(final BundleContext bundleContext) { - this.bundleContext = bundleContext; - } + + @Override public Collection getProviderFunctionality() { diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java index 763e6ad3ca..a7c8843fcf 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java @@ -9,29 +9,7 @@ */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.osgi.framework.BundleContext; public class BindingAsyncDataBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModuleFactory { - - - - @Override - public BindingAsyncDataBrokerImplModule instantiateModule(final String instanceName, - final DependencyResolver dependencyResolver, final BindingAsyncDataBrokerImplModule oldModule, - final AutoCloseable oldInstance, final BundleContext bundleContext) { - BindingAsyncDataBrokerImplModule module = super.instantiateModule(instanceName, dependencyResolver, oldModule, oldInstance, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public BindingAsyncDataBrokerImplModule instantiateModule(final String instanceName, - final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - // TODO Auto-generated method stub - BindingAsyncDataBrokerImplModule module = super.instantiateModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java index 188272fb60..61e7a2e6a2 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java @@ -1,96 +1,85 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -/** - * Generated file - - * Generated from: yang module name: opendaylight-sal-binding-broker-impl yang module local name: binding-broker-impl - * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - * Generated at: Wed Nov 20 17:33:01 CET 2013 - * - * Do not modify this file unless it is present under src/main directory - */ -package org.opendaylight.controller.config.yang.md.sal.binding.impl; - -import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder; -import org.opendaylight.controller.sal.binding.impl.RootBindingAwareBroker; -import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl; -import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl; -import org.opendaylight.controller.sal.binding.impl.forward.DomForwardingUtils; -import org.osgi.framework.BundleContext; - -/** -* -*/ -public final class BindingBrokerImplModule extends - org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModule { - - private BundleContext bundleContext; - - public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, - final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, - final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, - final BindingBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void validate() { - super.validate(); - } - - @Override - public java.lang.AutoCloseable createInstance() { - - RootBindingAwareBroker broker; - if (DomForwardingUtils.isDomForwardedBroker(getDataBrokerDependency())) { - broker = createForwardedBroker(); - } else { - broker = createStandaloneBroker(); - } - broker.start(); - return broker; - } - - private RootBindingAwareBroker createStandaloneBroker() { - RootBindingAwareBroker broker = new RootBindingAwareBroker(getIdentifier().getInstanceName()); - - broker.setLegacyDataBroker(getDataBrokerDependency()); - broker.setNotificationBroker(getNotificationServiceDependency()); - broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier())); - // FIXME: Also set Async Data Broker - return broker; - } - - private RootBindingAwareBroker createForwardedBroker() { - DomForwardedBindingBrokerImpl broker = new DomForwardedBindingBrokerImpl(getIdentifier().getInstanceName()); - - broker.setLegacyDataBroker(getDataBrokerDependency()); - broker.setNotificationBroker(getNotificationServiceDependency()); - broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier())); - - broker.getMountManager().setDataCommitExecutor(SingletonHolder.getDefaultCommitExecutor()); - broker.getMountManager().setNotificationExecutor(SingletonHolder.getDefaultNotificationExecutor()); - - // FIXME: Also set Async Data Broker - DomForwardingUtils.reuseForwardingFrom(broker, broker.getDataBroker()); - broker.startForwarding(); - return broker; - } - - public BundleContext getBundleContext() { - return bundleContext; - } - - public void setBundleContext(final BundleContext bundleContext) { - this.bundleContext = bundleContext; - } -} +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +/** + * Generated file + + * Generated from: yang module name: opendaylight-sal-binding-broker-impl yang module local name: binding-broker-impl + * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator + * Generated at: Wed Nov 20 17:33:01 CET 2013 + * + * Do not modify this file unless it is present under src/main directory + */ +package org.opendaylight.controller.config.yang.md.sal.binding.impl; + +import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder; +import org.opendaylight.controller.sal.binding.impl.RootBindingAwareBroker; +import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl; +import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl; +import org.opendaylight.controller.sal.binding.impl.forward.DomForwardingUtils; + +/** +* +*/ +public final class BindingBrokerImplModule extends + org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModule { + + public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, + final BindingBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void validate() { + super.validate(); + } + + @Override + public java.lang.AutoCloseable createInstance() { + + RootBindingAwareBroker broker; + if (DomForwardingUtils.isDomForwardedBroker(getDataBrokerDependency())) { + broker = createForwardedBroker(); + } else { + broker = createStandaloneBroker(); + } + broker.start(); + return broker; + } + + private RootBindingAwareBroker createStandaloneBroker() { + RootBindingAwareBroker broker = new RootBindingAwareBroker(getIdentifier().getInstanceName()); + + broker.setLegacyDataBroker(getDataBrokerDependency()); + broker.setNotificationBroker(getNotificationServiceDependency()); + broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier())); + broker.setDataBroker(getRootDataBrokerDependency()); + return broker; + } + + private RootBindingAwareBroker createForwardedBroker() { + DomForwardedBindingBrokerImpl broker = new DomForwardedBindingBrokerImpl(getIdentifier().getInstanceName()); + + broker.setLegacyDataBroker(getDataBrokerDependency()); + broker.setNotificationBroker(getNotificationServiceDependency()); + broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier())); + + broker.getMountManager().setDataCommitExecutor(SingletonHolder.getDefaultCommitExecutor()); + broker.getMountManager().setNotificationExecutor(SingletonHolder.getDefaultNotificationExecutor()); + + broker.setDataBroker(getRootDataBrokerDependency()); + DomForwardingUtils.reuseForwardingFrom(broker, broker.getDataBroker()); + broker.startForwarding(); + return broker; + } +} diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java index a11a7d67f5..181b568cf5 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java @@ -16,30 +16,10 @@ */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; /** * */ public class BindingBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModuleFactory { - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) { - BindingBrokerImplModule module = (BindingBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, - DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception { - BindingBrokerImplModule module = (BindingBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java index 7357926b9e..4a4e800078 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java @@ -5,8 +5,8 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ -package org.opendaylight.controller.config.yang.md.sal.binding.impl; - +package org.opendaylight.controller.config.yang.md.sal.binding.impl; + import java.util.concurrent.ExecutorService; import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder; @@ -16,85 +16,64 @@ import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndepende import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedDataBrokerImpl; import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; - -/** -* -*/ -public final class DataBrokerImplModule extends - org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModule { - - private BundleContext bundleContext; - - public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, - org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, - org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, - DataBrokerImplModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void validate() { - super.validate(); - } - - @Override - public java.lang.AutoCloseable createInstance() { - RootDataBrokerImpl dataBindingBroker; - - - ExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor(); - BindingIndependentMappingService potentialMapping = resolveMappingServiceDependency(); - if (getDomBrokerDependency() != null && potentialMapping != null) { - - dataBindingBroker = createDomConnectedBroker(listeningExecutor,potentialMapping); - } else { - dataBindingBroker = createStandAloneBroker(listeningExecutor); - } - dataBindingBroker.registerRuntimeBean(getRootRuntimeBeanRegistratorWrapper()); - dataBindingBroker.setNotificationExecutor(SingletonHolder.getDefaultChangeEventExecutor()); - return dataBindingBroker; - } - private BindingIndependentMappingService resolveMappingServiceDependency() { - if(getMappingService() != null) { - return getMappingServiceDependency(); - } - - ServiceReference potentialMappingService = bundleContext.getServiceReference(BindingIndependentMappingService.class); - if(potentialMappingService != null) { - return bundleContext.getService(potentialMappingService); - } - return null; - } - - private RootDataBrokerImpl createStandAloneBroker(ExecutorService listeningExecutor) { - RootDataBrokerImpl broker = new RootDataBrokerImpl(); - broker.setExecutor(listeningExecutor); - return broker; - } - - private RootDataBrokerImpl createDomConnectedBroker(ExecutorService listeningExecutor, BindingIndependentMappingService mappingService) { - DomForwardedDataBrokerImpl forwardedBroker = new DomForwardedDataBrokerImpl(); - forwardedBroker.setExecutor(listeningExecutor); - BindingIndependentConnector connector = BindingDomConnectorDeployer.createConnector(mappingService); - getDomBrokerDependency().registerProvider(forwardedBroker, getBundleContext()); - ProviderSession domContext = forwardedBroker.getDomProviderContext(); - forwardedBroker.setConnector(connector); - forwardedBroker.setDomProviderContext(domContext); - forwardedBroker.startForwarding(); - return forwardedBroker; - } - - public BundleContext getBundleContext() { - return bundleContext; - } - - public void setBundleContext(BundleContext bundleContext2) { - this.bundleContext = bundleContext2; - } -} + +/** +* +*/ +public final class DataBrokerImplModule extends + org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModule { + + public DataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public DataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, + final DataBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void validate() { + super.validate(); + } + + @Override + public java.lang.AutoCloseable createInstance() { + RootDataBrokerImpl dataBindingBroker; + + + ExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor(); + BindingIndependentMappingService potentialMapping = getMappingServiceDependency(); + if (getDomBrokerDependency() != null && potentialMapping != null) { + + dataBindingBroker = createDomConnectedBroker(listeningExecutor,potentialMapping); + } else { + dataBindingBroker = createStandAloneBroker(listeningExecutor); + } + dataBindingBroker.registerRuntimeBean(getRootRuntimeBeanRegistratorWrapper()); + dataBindingBroker.setNotificationExecutor(SingletonHolder.getDefaultChangeEventExecutor()); + return dataBindingBroker; + } + + + private RootDataBrokerImpl createStandAloneBroker(final ExecutorService listeningExecutor) { + RootDataBrokerImpl broker = new RootDataBrokerImpl(); + broker.setExecutor(listeningExecutor); + return broker; + } + + private RootDataBrokerImpl createDomConnectedBroker(final ExecutorService listeningExecutor, final BindingIndependentMappingService mappingService) { + DomForwardedDataBrokerImpl forwardedBroker = new DomForwardedDataBrokerImpl(); + forwardedBroker.setExecutor(listeningExecutor); + BindingIndependentConnector connector = BindingDomConnectorDeployer.createConnector(mappingService); + getDomBrokerDependency().registerProvider(forwardedBroker, null); + ProviderSession domContext = forwardedBroker.getDomProviderContext(); + forwardedBroker.setConnector(connector); + forwardedBroker.setDomProviderContext(domContext); + forwardedBroker.startForwarding(); + return forwardedBroker; + } + +} diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java index 9ce3ebf73f..d3fc5ac215 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java @@ -7,10 +7,6 @@ */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; /** * @@ -18,21 +14,4 @@ import org.osgi.framework.BundleContext; public class DataBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModuleFactory { - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) { - DataBrokerImplModule module = (DataBrokerImplModule) super.createModule(instanceName, dependencyResolver, - bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, - DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception { - DataBrokerImplModule module = (DataBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, - bundleContext); - module.setBundleContext(bundleContext); - return module; - } - } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java index 7467e544fd..0ea30f7e66 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java @@ -19,7 +19,6 @@ import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; import org.opendaylight.controller.sal.core.api.Provider; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService; -import org.osgi.framework.BundleContext; import com.google.common.util.concurrent.ListeningExecutorService; @@ -30,8 +29,6 @@ public final class ForwardedCompatibleDataBrokerImplModule extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractForwardedCompatibleDataBrokerImplModule implements Provider { - private BundleContext bundleContext; - public ForwardedCompatibleDataBrokerImplModule( final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { @@ -57,7 +54,7 @@ public final class ForwardedCompatibleDataBrokerImplModule extends BindingIndependentMappingService mappingService = getBindingMappingServiceDependency(); Broker domBroker = getDomAsyncBrokerDependency(); - ProviderSession session = domBroker.registerProvider(this, getBundleContext()); + ProviderSession session = domBroker.registerProvider(this, null); DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class); SchemaService schemaService = session.getService(SchemaService.class); ForwardedBackwardsCompatibleDataBroker dataBroker = new ForwardedBackwardsCompatibleDataBroker(domDataBroker, @@ -68,14 +65,6 @@ public final class ForwardedCompatibleDataBrokerImplModule extends return dataBroker; } - public BundleContext getBundleContext() { - return bundleContext; - } - - public void setBundleContext(final BundleContext bundleContext2) { - this.bundleContext = bundleContext2; - } - @Override public void onSessionInitiated(final ProviderSession session) { diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.java index f01977503e..5b5fb45fd9 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.java @@ -7,10 +7,6 @@ */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; /** @@ -19,20 +15,4 @@ import org.osgi.framework.BundleContext; public class ForwardedCompatibleDataBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractForwardedCompatibleDataBrokerImplModuleFactory { - - @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - ForwardedCompatibleDataBrokerImplModule module = (ForwardedCompatibleDataBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, - final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { - ForwardedCompatibleDataBrokerImplModule module = (ForwardedCompatibleDataBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java index 003f57cd72..6b519955ac 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java @@ -120,7 +120,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { */ public Optional> toBinding( final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) - throws DeserializationException { + throws DeserializationException { PathArgument lastArgument = Iterables.getLast(normalized.getPathArguments()); // Used instance-identifier codec do not support serialization of last @@ -137,7 +137,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { private Optional> toBindingAugmented( final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) - throws DeserializationException { + throws DeserializationException { Optional> potential = toBindingImpl(normalized); // Shorthand check, if codec already supports deserialization // of AugmentationIdentifier we will return @@ -154,9 +154,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { // path. LOG.trace("Looking for candidates to match {}", normalized); for (QName child : lastArgument.getPossibleChildNames()) { - org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier( - ImmutableList. builder().addAll(normalized.getPathArguments()).add(new NodeIdentifier(child)) - .build()); + org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = normalized.node(child); try { if (isNotRepresentable(childPath)) { LOG.trace("Path {} is not BI-representable, skipping it", childPath); @@ -189,7 +187,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { private Optional> toBindingImpl( final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) - throws DeserializationException { + throws DeserializationException { org.opendaylight.yangtools.yang.data.api.InstanceIdentifier legacyPath; try { @@ -219,7 +217,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { private DataNormalizationOperation findNormalizationOperation( final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) - throws DataNormalizationException { + throws DataNormalizationException { DataNormalizationOperation current = legacyToNormalized.getRootOperation(); for (PathArgument arg : normalized.getPathArguments()) { current = current.getChild(arg); @@ -264,7 +262,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { public Optional, DataObject>> toBinding( final Entry> normalized) - throws DeserializationException { + throws DeserializationException { Optional> potentialPath = toBinding(normalized.getKey()); if (potentialPath.isPresent()) { InstanceIdentifier bindingPath = potentialPath.get(); @@ -375,18 +373,18 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener { try { return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(), new Supplier() { - @Override - public Class get() { - Type listResult = ClassLoaderUtils.getFirstGenericParameter(method - .getGenericReturnType()); - if (listResult instanceof Class - && DataObject.class.isAssignableFrom((Class) listResult)) { - return (Class) listResult; - } - return null; - } - - }); + @Override + public Class get() { + Type listResult = ClassLoaderUtils.getFirstGenericParameter(method + .getGenericReturnType()); + if (listResult instanceof Class + && DataObject.class.isAssignableFrom((Class) listResult)) { + return (Class) listResult; + } + return null; + } + + }); } catch (Exception e) { LOG.debug("Could not get YANG modeled entity for {}", method, e); return null; diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang b/opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang index 4456dea77f..cee4b1efb3 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang +++ b/opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang @@ -105,7 +105,7 @@ module opendaylight-sal-binding-broker-impl { container data-broker { uses config:service-ref { refine type { - mandatory true; + mandatory false; config:required-identity sal:binding-data-broker; } } @@ -119,6 +119,15 @@ module opendaylight-sal-binding-broker-impl { } } } + + container root-data-broker { + uses config:service-ref { + refine type { + mandatory false; + config:required-identity sal:binding-async-data-broker; + } + } + } } } diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java index 623b2fdd63..1ea56381ef 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java +++ b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java @@ -66,6 +66,7 @@ import com.google.common.base.Predicate; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.MutableClassToInstanceMap; import com.google.common.util.concurrent.ListeningExecutorService; public class BindingTestContext implements AutoCloseable { @@ -160,11 +161,10 @@ public class BindingTestContext implements AutoCloseable { newDOMDataBroker = new DOMDataBrokerImpl(newDatastores, executor); - biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker); + biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker,mockSchemaService); mockSchemaService.registerSchemaServiceListener(configStore); mockSchemaService.registerSchemaServiceListener(operStore); - mockSchemaService.registerSchemaServiceListener(biCompatibleBroker); biDataLegacyBroker = biCompatibleBroker; } @@ -338,8 +338,10 @@ public class BindingTestContext implements AutoCloseable { private void startDomBroker() { checkState(executor != null); - biBrokerImpl = new BrokerImpl(); - biBrokerImpl.setRouter(new SchemaAwareRpcBroker("/", mockSchemaService)); + + SchemaAwareRpcBroker router = new SchemaAwareRpcBroker("/", mockSchemaService); + ClassToInstanceMap services = MutableClassToInstanceMap.create(); + biBrokerImpl = new BrokerImpl(router,services); } diff --git a/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java b/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java index 7ce475dd59..2b9694bed7 100644 --- a/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java +++ b/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java @@ -14,6 +14,7 @@ import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; + import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -21,6 +22,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; + import org.opendaylight.yangtools.concepts.Identifiable; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; @@ -156,7 +158,7 @@ public abstract class DataNormalizationOperation impleme } private static abstract class CompositeNodeNormalizationOperation extends - DataNormalizationOperation { + DataNormalizationOperation { protected CompositeNodeNormalizationOperation(final T identifier) { super(identifier); @@ -218,7 +220,7 @@ public abstract class DataNormalizationOperation impleme } private static abstract class DataContainerNormalizationOperation extends - CompositeNodeNormalizationOperation { + CompositeNodeNormalizationOperation { private final DataNodeContainer schema; private final Map> byQName; @@ -276,7 +278,7 @@ public abstract class DataNormalizationOperation impleme } private static final class ListItemNormalization extends - DataContainerNormalizationOperation { + DataContainerNormalizationOperation { private final List keyDefinition; @@ -356,7 +358,7 @@ public abstract class DataNormalizationOperation impleme } private static abstract class MixinNormalizationOp extends - CompositeNodeNormalizationOperation { + CompositeNodeNormalizationOperation { protected MixinNormalizationOp(final T identifier) { super(identifier); @@ -615,25 +617,25 @@ public abstract class DataNormalizationOperation impleme private static class AnyXmlNormalization extends DataNormalizationOperation { - protected AnyXmlNormalization( NodeIdentifier identifier ) { + protected AnyXmlNormalization( final NodeIdentifier identifier ) { super( identifier ); } @Override - public DataNormalizationOperation getChild( PathArgument child ) throws DataNormalizationException { + public DataNormalizationOperation getChild( final PathArgument child ) throws DataNormalizationException { return null; } @Override - public DataNormalizationOperation getChild( QName child ) throws DataNormalizationException { + public DataNormalizationOperation getChild( final QName child ) throws DataNormalizationException { return null; } @Override - public NormalizedNode normalize( Node legacyData ) { + public NormalizedNode normalize( final Node legacyData ) { NormalizedNodeAttrBuilder, AnyXmlNode> builder = Builders.anyXmlBuilder().withNodeIdentifier( - new NodeIdentifier( legacyData.getNodeType() ) ); + new NodeIdentifier( legacyData.getNodeType() ) ); builder.withValue(legacyData); return builder.build(); } @@ -644,7 +646,7 @@ public abstract class DataNormalizationOperation impleme } @Override - public NormalizedNode createDefault( PathArgument currentArg ) { + public NormalizedNode createDefault( final PathArgument currentArg ) { return null; } } @@ -694,7 +696,7 @@ public abstract class DataNormalizationOperation impleme for (DataSchemaNode child : augmentation.getChildNodes()) { potentialChildren.add(child.getQName()); } - return new AugmentationIdentifier(null, potentialChildren.build()); + return new AugmentationIdentifier(potentialChildren.build()); } private static DataNodeContainer augmentationProxy(final AugmentationSchema augmentation, final DataNodeContainer schema) { diff --git a/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java b/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java index ec8ce6ecd5..113d3dc9f7 100644 --- a/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java +++ b/opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java @@ -14,10 +14,12 @@ import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; + import java.util.AbstractMap; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; + import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; @@ -48,7 +50,7 @@ public class DataNormalizer { ImmutableList.Builder normalizedArgs = ImmutableList.builder(); DataNormalizationOperation currentOp = operation; - Iterator arguments = legacy.getPath().iterator(); + Iterator arguments = legacy.getPathArguments().iterator(); try { while (arguments.hasNext()) { @@ -67,7 +69,7 @@ public class DataNormalizer { throw new IllegalArgumentException(String.format("Failed to normalize path %s", legacy), e); } - return new InstanceIdentifier(normalizedArgs.build()); + return InstanceIdentifier.create(normalizedArgs.build()); } public Map.Entry> toNormalized( @@ -81,7 +83,7 @@ public class DataNormalizer { InstanceIdentifier normalizedPath = toNormalized(legacyPath); DataNormalizationOperation currentOp = operation; - for (PathArgument arg : normalizedPath.getPath()) { + for (PathArgument arg : normalizedPath.getPathArguments()) { try { currentOp = currentOp.getChild(arg); } catch (DataNormalizationException e) { @@ -103,9 +105,7 @@ public class DataNormalizer { if (potentialOp.getIdentifier() instanceof AugmentationIdentifier) { currentOp = potentialOp; - ArrayList reworkedArgs = new ArrayList<>(normalizedPath.getPath()); - reworkedArgs.add(potentialOp.getIdentifier()); - normalizedPath = new InstanceIdentifier(reworkedArgs); + normalizedPath = normalizedPath.node(potentialOp.getIdentifier()); } } @@ -117,15 +117,14 @@ public class DataNormalizer { public InstanceIdentifier toLegacy(final InstanceIdentifier normalized) throws DataNormalizationException { ImmutableList.Builder legacyArgs = ImmutableList.builder(); - PathArgument previous = null; DataNormalizationOperation currentOp = operation; - for (PathArgument normalizedArg : normalized.getPath()) { + for (PathArgument normalizedArg : normalized.getPathArguments()) { currentOp = currentOp.getChild(normalizedArg); if(!currentOp.isMixin()) { legacyArgs.add(normalizedArg); } } - return new InstanceIdentifier(legacyArgs.build()); + return InstanceIdentifier.create(legacyArgs.build()); } public CompositeNode toLegacy(final InstanceIdentifier normalizedPath, final NormalizedNode normalizedData) { diff --git a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java index ce861f7e7a..dcb90a83ba 100644 --- a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java +++ b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java @@ -14,9 +14,11 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; + import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; @@ -26,6 +28,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; + import org.junit.Test; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; @@ -68,7 +71,7 @@ public class DataNormalizerTest { Class nodeClass; Object nodeData; // List for a container, value Object for a leaf - NormalizedNodeData(PathArgument nodeID, Class nodeClass, Object nodeData) { + NormalizedNodeData(final PathArgument nodeID, final Class nodeClass, final Object nodeData) { this.nodeID = nodeID; this.nodeClass = nodeClass; this.nodeData = nodeData; @@ -78,9 +81,9 @@ public class DataNormalizerTest { static class LegacyNodeData { QName nodeKey; Object nodeData; // List for a CompositeNode, value Object for a - // SimpeNode + // SimpeNode - LegacyNodeData(QName nodeKey, Object nodeData) { + LegacyNodeData(final QName nodeKey, final Object nodeData) { this.nodeKey = nodeKey; this.nodeData = nodeData; } @@ -144,13 +147,13 @@ public class DataNormalizerTest { OUTER_LIST_QNAME, ID_QNAME, OUTER_LIST_ID }, OUTER_CHOICE_QNAME, TWO_QNAME); } - private void verifyNormalizedInstanceIdentifier(InstanceIdentifier actual, Object... expPath) { + private void verifyNormalizedInstanceIdentifier(final InstanceIdentifier actual, final Object... expPath) { assertNotNull("Actual InstanceIdentifier is null", actual); - assertEquals("InstanceIdentifier path length", expPath.length, actual.getPath().size()); + assertEquals("InstanceIdentifier path length", expPath.length, Iterables.size(actual.getPathArguments())); for (int i = 0; i < expPath.length; i++) { - PathArgument actualArg = actual.getPath().get(i); + PathArgument actualArg = Iterables.get(actual.getPathArguments(), i); if (expPath[i] instanceof Object[]) { // NodeIdentifierWithPredicates Object[] exp = (Object[]) expPath[i]; assertEquals("Actual path arg " + (i + 1) + " class", NodeIdentifierWithPredicates.class, @@ -256,12 +259,12 @@ public class DataNormalizerTest { expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name1"), expectSimpleNode(VALUE_QNAME, "inner-value1")), - expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name2"), - expectSimpleNode(VALUE_QNAME, "inner-value2"))), - expectCompositeNode(OUTER_LIST_QNAME, expectSimpleNode(ID_QNAME, outerListID2), - expectSimpleNode(ONE_QNAME, "one")), - expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed1")), - expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed2")))); + expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name2"), + expectSimpleNode(VALUE_QNAME, "inner-value2"))), + expectCompositeNode(OUTER_LIST_QNAME, expectSimpleNode(ID_QNAME, outerListID2), + expectSimpleNode(ONE_QNAME, "one")), + expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed1")), + expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed2")))); // Conversion of Mixin type nodes is not supported. @@ -366,12 +369,12 @@ public class DataNormalizerTest { expectSimpleNode(AUGMENTED_LEAF_QNAME, "augmented-value")))); } - private boolean isOrdered(QName nodeName) { + private boolean isOrdered(final QName nodeName) { return ORDERED_LEAF_LIST_QNAME.equals(nodeName) || INNER_LIST_QNAME.equals(nodeName); } @SuppressWarnings("unchecked") - private void verifyLegacyNode(Node actual, LegacyNodeData expNodeData) { + private void verifyLegacyNode(final Node actual, final LegacyNodeData expNodeData) { assertNotNull("Actual Node is null", actual); assertTrue("Expected CompositeNode instance", actual instanceof CompositeNode); @@ -390,7 +393,7 @@ public class DataNormalizerTest { Collections.sort(unorderdChildData, new Comparator() { @Override - public int compare(LegacyNodeData arg1, LegacyNodeData arg2) { + public int compare(final LegacyNodeData arg1, final LegacyNodeData arg2) { if (!(arg1.nodeData instanceof List) && !(arg2.nodeData instanceof List)) { // if neither is a list, just compare them String str1 = arg1.nodeKey.getLocalName() + arg1.nodeData; @@ -446,7 +449,7 @@ public class DataNormalizerTest { Collections.sort(unorderedChildNodes, new Comparator>() { @Override - public int compare(Node n1, Node n2) { + public int compare(final Node n1, final Node n2) { if (n1 instanceof SimpleNode && n2 instanceof SimpleNode) { // if they're SimpleNodes just compare their strings String str1 = n1.getKey().getLocalName() + ((SimpleNode)n1).getValue(); @@ -501,7 +504,7 @@ public class DataNormalizerTest { assertEquals("Child node QName", expData.nodeKey, actualChild.getKey()); if (expData.nodeData instanceof List) { // List represents a - // composite node + // composite node verifyLegacyNode(actualChild, expData); } else { // else a simple node assertTrue("Expected SimpleNode instance", actualChild instanceof SimpleNode); @@ -515,11 +518,11 @@ public class DataNormalizerTest { } } - private LegacyNodeData expectCompositeNode(QName key, LegacyNodeData... childData) { + private LegacyNodeData expectCompositeNode(final QName key, final LegacyNodeData... childData) { return new LegacyNodeData(key, Lists.newArrayList(childData)); } - private LegacyNodeData expectSimpleNode(QName key, Object value) { + private LegacyNodeData expectSimpleNode(final QName key, final Object value) { return new LegacyNodeData(key, value); } @@ -561,7 +564,7 @@ public class DataNormalizerTest { } Entry> normalizedNodeEntry = normalizer - .toNormalized(new AbstractMap.SimpleEntry(new InstanceIdentifier( + .toNormalized(new AbstractMap.SimpleEntry(InstanceIdentifier.create( ImmutableList. of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance())); verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME); @@ -583,25 +586,25 @@ public class DataNormalizerTest { expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name3", expectLeafNode(NAME_QNAME, "inner-name3"), expectLeafNode(VALUE_QNAME, "inner-value3")), - expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name2", - expectLeafNode(NAME_QNAME, "inner-name2"), - expectLeafNode(VALUE_QNAME, "inner-value2")), - expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name1", - expectLeafNode(NAME_QNAME, "inner-name1"), - expectLeafNode(VALUE_QNAME, "inner-value1")))), - expectMapEntryNode( - OUTER_LIST_QNAME, - ID_QNAME, - 20, - expectLeafNode(ID_QNAME, 20), - expectChoiceNode(OUTER_CHOICE_QNAME, expectLeafNode(TWO_QNAME, "two"), - expectLeafNode(THREE_QNAME, "three")))), - expectUnkeyedListNode( - UNKEYED_LIST_QNAME, - expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME, - expectLeafNode(NAME_QNAME, "unkeyed-name1")), - expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME, - expectLeafNode(NAME_QNAME, "unkeyed-name2"))))); + expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name2", + expectLeafNode(NAME_QNAME, "inner-name2"), + expectLeafNode(VALUE_QNAME, "inner-value2")), + expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name1", + expectLeafNode(NAME_QNAME, "inner-name1"), + expectLeafNode(VALUE_QNAME, "inner-value1")))), + expectMapEntryNode( + OUTER_LIST_QNAME, + ID_QNAME, + 20, + expectLeafNode(ID_QNAME, 20), + expectChoiceNode(OUTER_CHOICE_QNAME, expectLeafNode(TWO_QNAME, "two"), + expectLeafNode(THREE_QNAME, "three")))), + expectUnkeyedListNode( + UNKEYED_LIST_QNAME, + expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME, + expectLeafNode(NAME_QNAME, "unkeyed-name1")), + expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME, + expectLeafNode(NAME_QNAME, "unkeyed-name2"))))); } @Test @@ -625,7 +628,7 @@ public class DataNormalizerTest { testBuilder.add(anyXmlLegacy); Entry> normalizedNodeEntry = normalizer - .toNormalized(new AbstractMap.SimpleEntry(new InstanceIdentifier( + .toNormalized(new AbstractMap.SimpleEntry(InstanceIdentifier.create( ImmutableList. of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance())); verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME); @@ -649,7 +652,7 @@ public class DataNormalizerTest { testBuilder.add(outerContBuilder.toInstance()); Entry> normalizedNodeEntry = normalizer - .toNormalized(new AbstractMap.SimpleEntry(new InstanceIdentifier( + .toNormalized(new AbstractMap.SimpleEntry(InstanceIdentifier.create( ImmutableList. of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance())); verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME); @@ -661,7 +664,7 @@ public class DataNormalizerTest { expectContainerNode(TEST_QNAME, expectContainerNode(OUTER_CONTAINER_QNAME, expAugmentation))); normalizedNodeEntry = normalizer.toNormalized(new AbstractMap.SimpleEntry( - new InstanceIdentifier(Lists.newArrayList(new NodeIdentifier(TEST_QNAME), new NodeIdentifier( + InstanceIdentifier.create(Lists.newArrayList(new NodeIdentifier(TEST_QNAME), new NodeIdentifier( OUTER_CONTAINER_QNAME))), outerContBuilder.toInstance())); verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME, OUTER_CONTAINER_QNAME, @@ -687,7 +690,7 @@ public class DataNormalizerTest { } Entry> normalizedNodeEntry = normalizer - .toNormalized(new AbstractMap.SimpleEntry(new InstanceIdentifier( + .toNormalized(new AbstractMap.SimpleEntry(InstanceIdentifier.create( ImmutableList. of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance())); verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME); @@ -700,14 +703,14 @@ public class DataNormalizerTest { expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value1"), expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value2"), expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value3")), - expectOrderedLeafSetNode(ORDERED_LEAF_LIST_QNAME, - expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value3"), - expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value2"), - expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value1")))); + expectOrderedLeafSetNode(ORDERED_LEAF_LIST_QNAME, + expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value3"), + expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value2"), + expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value1")))); } @SuppressWarnings("unchecked") - private void verifyNormalizedNode(NormalizedNode actual, NormalizedNodeData expNodeData) { + private void verifyNormalizedNode(final NormalizedNode actual, final NormalizedNodeData expNodeData) { Class expNodeClass = expNodeData.nodeClass; PathArgument expNodeID = expNodeData.nodeID; @@ -743,18 +746,18 @@ public class DataNormalizerTest { NormalizedNodeData expChildData = expNodeClass.equals(UnkeyedListNode.class) ? expChildDataList .remove(0) : expChildDataMap.remove(actualChild.getIdentifier()); - assertNotNull( - "Unexpected child node " + actualChild.getClass() + " with identifier " - + actualChild.getIdentifier() + " for parent node " + actual.getClass() - + " with identifier " + actual.getIdentifier(), expChildData); + assertNotNull( + "Unexpected child node " + actualChild.getClass() + " with identifier " + + actualChild.getIdentifier() + " for parent node " + actual.getClass() + + " with identifier " + actual.getIdentifier(), expChildData); - if (orderingMap != null) { - assertEquals("Order index for child node " + actualChild.getIdentifier(), - orderingMap.get(actualChild.getIdentifier()), Integer.valueOf(i)); - } + if (orderingMap != null) { + assertEquals("Order index for child node " + actualChild.getIdentifier(), + orderingMap.get(actualChild.getIdentifier()), Integer.valueOf(i)); + } - verifyNormalizedNode(actualChild, expChildData); - i++; + verifyNormalizedNode(actualChild, expChildData); + i++; } if (expNodeClass.equals(UnkeyedListNode.class)) { @@ -771,62 +774,62 @@ public class DataNormalizerTest { } } - private NormalizedNodeData expectOrderedLeafSetNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectOrderedLeafSetNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), OrderedLeafSetNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectLeafSetNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectLeafSetNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), LeafSetNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectLeafSetEntryNode(QName nodeName, Object value) { + private NormalizedNodeData expectLeafSetEntryNode(final QName nodeName, final Object value) { return new NormalizedNodeData(new NodeWithValue(nodeName, value), LeafSetEntryNode.class, value); } - private NormalizedNodeData expectUnkeyedListNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectUnkeyedListNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), UnkeyedListNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectUnkeyedListEntryNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectUnkeyedListEntryNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), UnkeyedListEntryNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectAugmentation(QName augmentedNodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectAugmentation(final QName augmentedNodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new AugmentationIdentifier(Sets.newHashSet(augmentedNodeName)), AugmentationNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectAnyXmlNode(QName nodeName, Object value) { + private NormalizedNodeData expectAnyXmlNode(final QName nodeName, final Object value) { return new NormalizedNodeData(new NodeIdentifier(nodeName), AnyXmlNode.class, value); } - private NormalizedNodeData expectContainerNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectContainerNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), ContainerNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectChoiceNode(QName nodeName, NormalizedNodeData... childData) { + private NormalizedNodeData expectChoiceNode(final QName nodeName, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(nodeName), ChoiceNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectLeafNode(QName nodeName, Object value) { + private NormalizedNodeData expectLeafNode(final QName nodeName, final Object value) { return new NormalizedNodeData(new NodeIdentifier(nodeName), LeafNode.class, value); } - private NormalizedNodeData expectMapEntryNode(QName nodeName, QName key, Object value, - NormalizedNodeData... childData) { + private NormalizedNodeData expectMapEntryNode(final QName nodeName, final QName key, final Object value, + final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifierWithPredicates(nodeName, key, value), MapEntryNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectMapNode(QName key, NormalizedNodeData... childData) { + private NormalizedNodeData expectMapNode(final QName key, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(key), MapNode.class, Lists.newArrayList(childData)); } - private NormalizedNodeData expectOrderedMapNode(QName key, NormalizedNodeData... childData) { + private NormalizedNodeData expectOrderedMapNode(final QName key, final NormalizedNodeData... childData) { return new NormalizedNodeData(new NodeIdentifier(key), OrderedMapNode.class, Lists.newArrayList(childData)); } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java index 767785dbf1..998d884b0c 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java @@ -8,10 +8,26 @@ package org.opendaylight.controller.config.yang.md.sal.dom.impl; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleDataBroker; +import org.opendaylight.controller.sal.core.api.BrokerService; +import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; +import org.opendaylight.controller.sal.core.api.data.DataBrokerService; +import org.opendaylight.controller.sal.core.api.data.DataProviderService; import org.opendaylight.controller.sal.core.api.data.DataStore; -import org.opendaylight.controller.sal.dom.broker.BrokerConfigActivator; +import org.opendaylight.controller.sal.core.api.model.SchemaService; +import org.opendaylight.controller.sal.core.api.mount.MountProvisionService; +import org.opendaylight.controller.sal.core.api.mount.MountService; import org.opendaylight.controller.sal.dom.broker.BrokerImpl; -import org.osgi.framework.BundleContext; +import org.opendaylight.controller.sal.dom.broker.DataBrokerImpl; +import org.opendaylight.controller.sal.dom.broker.GlobalBundleScanningSchemaServiceImpl; +import org.opendaylight.controller.sal.dom.broker.MountPointManagerImpl; +import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter; +import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker; +import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProviders; +import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; + +import com.google.common.collect.ClassToInstanceMap; +import com.google.common.collect.MutableClassToInstanceMap; /** * @@ -19,8 +35,6 @@ import org.osgi.framework.BundleContext; public final class DomBrokerImplModule extends org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomBrokerImplModule { - private BundleContext bundleContext; - public DomBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { super(identifier, dependencyResolver); } @@ -36,23 +50,58 @@ public final class DomBrokerImplModule extends org.opendaylight.controller.confi @Override public java.lang.AutoCloseable createInstance() { - final BrokerImpl broker = new BrokerImpl(); - final BrokerConfigActivator activator = new BrokerConfigActivator(); - final DataStore store = getDataStoreDependency(); + final DataStore legacyStore = getDataStoreDependency(); final DOMDataBroker asyncBroker= getAsyncDataBrokerDependency(); - activator.start(broker, store, asyncBroker,getBundleContext()); + ClassToInstanceMap services = MutableClassToInstanceMap.create(); + + + SchemaService schemaService = getSchemaServiceImpl(); + services.putInstance(SchemaService.class, schemaService); + SchemaAwareRpcBroker router = new SchemaAwareRpcBroker("/", SchemaContextProviders + .fromSchemaService(schemaService)); + services.putInstance(RpcProvisionRegistry.class, router); + + final DataProviderService legacyData; + if(asyncBroker != null) { + services.putInstance(DOMDataBroker.class, asyncBroker); + legacyData = new BackwardsCompatibleDataBroker(asyncBroker,schemaService); + } else { + legacyData = createLegacyDataService(legacyStore,schemaService); + } + services.putInstance(DataProviderService.class,legacyData); + services.putInstance(DataBrokerService.class, legacyData); -// final DomBrokerImplRuntimeMXBean domBrokerRuntimeMXBean = new DomBrokerRuntimeMXBeanImpl(activator.getDataService()); -// getRootRuntimeBeanRegistratorWrapper().register(domBrokerRuntimeMXBean); - return broker; + + MountPointManagerImpl mountService = new MountPointManagerImpl(); + services.putInstance(MountService.class, mountService); + services.putInstance(MountProvisionService.class, mountService); + + return new BrokerImpl(router, services); } - private BundleContext getBundleContext() { - return this.bundleContext; + private DataProviderService createLegacyDataService(final DataStore legacyStore, final SchemaService schemaService) { + InstanceIdentifier rootPath = InstanceIdentifier.builder().toInstance(); + DataBrokerImpl dataService = new DataBrokerImpl(); + SchemaAwareDataStoreAdapter wrappedStore = new SchemaAwareDataStoreAdapter(); + wrappedStore.changeDelegate(legacyStore); + wrappedStore.setValidationEnabled(false); + + schemaService.registerSchemaServiceListener(wrappedStore); + + dataService.registerConfigurationReader(rootPath, wrappedStore); + dataService.registerCommitHandler(rootPath, wrappedStore); + dataService.registerOperationalReader(rootPath, wrappedStore); + return dataService; } - public void setBundleContext(final BundleContext bundleContext) { - this.bundleContext = bundleContext; + private SchemaService getSchemaServiceImpl() { + final SchemaService schemaService; + if(getRootSchemaService() != null) { + schemaService = getRootSchemaServiceDependency(); + } else { + schemaService = GlobalBundleScanningSchemaServiceImpl.getInstance(); + } + return schemaService; } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModuleFactory.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModuleFactory.java index 38f5009feb..f1fcb495aa 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModuleFactory.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModuleFactory.java @@ -7,10 +7,6 @@ */ package org.opendaylight.controller.config.yang.md.sal.dom.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; /** * @@ -18,19 +14,4 @@ import org.osgi.framework.BundleContext; public class DomBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomBrokerImplModuleFactory { - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) { - DomBrokerImplModule module = (DomBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, - DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception { - DomBrokerImplModule module = (DomBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java index d3852d28c5..69b17ee3c4 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java @@ -7,18 +7,16 @@ */ package org.opendaylight.controller.config.yang.md.sal.dom.impl; -import com.google.common.collect.ImmutableMap; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; +import java.util.concurrent.Executors; + import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl; import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore; import org.opendaylight.controller.sal.core.spi.data.DOMStore; -import org.osgi.framework.BundleContext; -import java.util.Hashtable; -import java.util.concurrent.Executors; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; /** * @@ -26,8 +24,6 @@ import java.util.concurrent.Executors; public final class DomInmemoryDataBrokerModule extends org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomInmemoryDataBrokerModule { - private BundleContext bundleContext; - public DomInmemoryDataBrokerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { super(identifier, dependencyResolver); @@ -70,17 +66,6 @@ public final class DomInmemoryDataBrokerModule extends DOMDataBrokerImpl newDataBroker = new DOMDataBrokerImpl(datastores, MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor())); - getBundleContext().registerService(DOMDataBroker.class, newDataBroker, new Hashtable()); - - return newDataBroker; } - - private BundleContext getBundleContext() { - return bundleContext; - } - - void setBundleContext(final BundleContext ctx) { - bundleContext = ctx; - } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModuleFactory.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModuleFactory.java index 91d42c48c1..56a51ed45e 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModuleFactory.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModuleFactory.java @@ -7,10 +7,6 @@ */ package org.opendaylight.controller.config.yang.md.sal.dom.impl; -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; /** * @@ -19,19 +15,4 @@ public class DomInmemoryDataBrokerModuleFactory extends org.opendaylight.control { - - @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - DomInmemoryDataBrokerModule module = (DomInmemoryDataBrokerModule) super.createModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, - final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { - DomInmemoryDataBrokerModule module = (DomInmemoryDataBrokerModule) super.createModule(instanceName, dependencyResolver, old, bundleContext); - module.setBundleContext(bundleContext); - return module; - } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java index fd24944018..fbc418dc2a 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java @@ -15,7 +15,6 @@ import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener; import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,43 +56,21 @@ org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractSchemaServiceImp @Override public java.lang.AutoCloseable createInstance() { - ServiceReference ref = getBundleContext().getServiceReference(SchemaService.class); - if (ref != null) { - return new GlobalSchemaServiceProxy(getBundleContext(), ref); - } - - GlobalBundleScanningSchemaServiceImpl newInstance = new GlobalBundleScanningSchemaServiceImpl(getBundleContext()); - newInstance.start(); - return newInstance; + return GlobalBundleScanningSchemaServiceImpl.getInstance(); } public class GlobalSchemaServiceProxy implements AutoCloseable, SchemaService, Delegator { - private BundleContext bundleContext; - private ServiceReference reference; private SchemaService delegate; - public GlobalSchemaServiceProxy(final BundleContext bundleContext, final ServiceReference ref) { - this.bundleContext = bundleContext; - this.reference = ref; - this.delegate = bundleContext.getService(reference); + public GlobalSchemaServiceProxy() { + this.delegate = GlobalBundleScanningSchemaServiceImpl.getInstance(); } @Override public void close() throws Exception { if (delegate != null) { delegate = null; - - try { - bundleContext.ungetService(reference); - } catch (IllegalStateException e) { - // Indicates the service was already unregistered which can happen normally - // on shutdown. - LOG.debug( "Error unregistering service", e ); - } - - reference = null; - bundleContext = null; } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java index 5b34fba69a..f361af948c 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java @@ -1,5 +1,7 @@ package org.opendaylight.controller.md.sal.dom.broker.impl.compat; +import javax.annotation.concurrent.ThreadSafe; + import org.opendaylight.controller.md.sal.common.api.RegistrationListener; import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler; import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration; @@ -11,6 +13,7 @@ import org.opendaylight.controller.sal.core.api.data.DataChangeListener; import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction; import org.opendaylight.controller.sal.core.api.data.DataProviderService; import org.opendaylight.controller.sal.core.api.data.DataValidator; +import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.yangtools.concepts.AbstractObjectRegistration; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.concepts.Registration; @@ -18,19 +21,18 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; +import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener; -public class BackwardsCompatibleDataBroker implements DataProviderService, SchemaContextListener { +@ThreadSafe +public class BackwardsCompatibleDataBroker implements DataProviderService { private final DOMDataBroker backingBroker; - private DataNormalizer normalizer; + private volatile DataNormalizer normalizer; + private final ListenerRegistration schemaReg; - public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl) { + public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl, final SchemaService schemaService) { backingBroker = newBiDataImpl; - } - - @Override - public void onGlobalContextUpdated(final SchemaContext ctx) { - normalizer = new DataNormalizer(ctx); + schemaReg = schemaService.registerSchemaServiceListener(new SchemaListener()); } @Override @@ -148,4 +150,13 @@ public class BackwardsCompatibleDataBroker implements DataProviderService, Schem return listener; } } + + private class SchemaListener implements SchemaContextListener { + + @Override + public void onGlobalContextUpdated(final SchemaContext ctx) { + normalizer = new DataNormalizer(ctx); + } + + } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java index b3fb7b6da8..27e322f23b 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java @@ -43,7 +43,7 @@ import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; public abstract class BackwardsCompatibleTransaction implements - DataModificationTransaction, Delegator { +DataModificationTransaction, Delegator { private static final Logger LOG = LoggerFactory.getLogger(BackwardsCompatibleTransaction.class); @@ -228,23 +228,23 @@ public abstract class BackwardsCompatibleTransaction currentArguments = new ArrayList<>(); - DataNormalizationOperation currentOp = getNormalizer().getRootOperation(); - Iterator iterator = normalizedPath.getPath().iterator(); - while(iterator.hasNext()) { - PathArgument currentArg = iterator.next(); - try { - currentOp = currentOp.getChild(currentArg); - } catch (DataNormalizationException e) { - throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", normalizedPath), e); + List currentArguments = new ArrayList<>(); + DataNormalizationOperation currentOp = getNormalizer().getRootOperation(); + Iterator iterator = normalizedPath.getPathArguments().iterator(); + while(iterator.hasNext()) { + PathArgument currentArg = iterator.next(); + try { + currentOp = currentOp.getChild(currentArg); + } catch (DataNormalizationException e) { + throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", normalizedPath), e); + } + currentArguments.add(currentArg); + InstanceIdentifier currentPath = InstanceIdentifier.create(currentArguments); + boolean isPresent = getDelegate().read(store, currentPath).get().isPresent(); + if(isPresent == false && iterator.hasNext()) { + getDelegate().merge(store, currentPath, currentOp.createDefault(currentArg)); + } } - currentArguments.add(currentArg); - InstanceIdentifier currentPath = new InstanceIdentifier(currentArguments); - boolean isPresent = getDelegate().read(store, currentPath).get().isPresent(); - if(isPresent == false && iterator.hasNext()) { - getDelegate().merge(store, currentPath, currentOp.createDefault(currentArg)); - } - } } catch (InterruptedException | ExecutionException e) { LOG.error("Exception durring read.",e); } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java deleted file mode 100644 index 3291afa061..0000000000 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.dom.broker; - -import java.util.Hashtable; - -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleDataBroker; -import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; -import org.opendaylight.controller.sal.core.api.data.DataBrokerService; -import org.opendaylight.controller.sal.core.api.data.DataProviderService; -import org.opendaylight.controller.sal.core.api.data.DataStore; -import org.opendaylight.controller.sal.core.api.model.SchemaService; -import org.opendaylight.controller.sal.core.api.mount.MountProvisionService; -import org.opendaylight.controller.sal.core.api.mount.MountService; -import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter; -import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker; -import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProviders; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; - -public class BrokerConfigActivator implements AutoCloseable { - - private static InstanceIdentifier ROOT = InstanceIdentifier.builder() - .toInstance(); - - private DataProviderService dataService; - - private ServiceRegistration dataReg = null; - private ServiceRegistration dataProviderReg = null; - private ServiceRegistration mountReg = null; - private ServiceRegistration mountProviderReg = null; - private SchemaService schemaService = null; - private ServiceRegistration rpcProvisionRegistryReg = null; - private MountPointManagerImpl mountService = null; - - private SchemaAwareDataStoreAdapter wrappedStore = null; - - public void start(final BrokerImpl broker, final DataStore store, - final DOMDataBroker asyncBroker, final BundleContext context) { - - final Hashtable emptyProperties = new Hashtable(); - broker.setBundleContext(context); - - final ServiceReference serviceRef = context - .getServiceReference(SchemaService.class); - schemaService = context. getService(serviceRef); - - broker.setRouter(new SchemaAwareRpcBroker("/", SchemaContextProviders - .fromSchemaService(schemaService))); - - if (asyncBroker == null) { - dataService = new DataBrokerImpl(); - dataProviderReg = context.registerService( - DataProviderService.class, dataService, emptyProperties); - - wrappedStore = new SchemaAwareDataStoreAdapter(); - wrappedStore.changeDelegate(store); - wrappedStore.setValidationEnabled(false); - context.registerService(SchemaServiceListener.class, wrappedStore, - emptyProperties); - - dataService.registerConfigurationReader(ROOT, wrappedStore); - dataService.registerCommitHandler(ROOT, wrappedStore); - dataService.registerOperationalReader(ROOT, wrappedStore); - } else { - BackwardsCompatibleDataBroker compatibleDataBroker = new BackwardsCompatibleDataBroker( - asyncBroker); - context.registerService(SchemaServiceListener.class, - compatibleDataBroker, emptyProperties); - dataService = compatibleDataBroker; - } - - mountService = new MountPointManagerImpl(); - dataReg = context.registerService(DataBrokerService.class, dataService, - emptyProperties); - mountReg = context.registerService(MountService.class, mountService, - emptyProperties); - mountProviderReg = context.registerService(MountProvisionService.class, - mountService, emptyProperties); - - rpcProvisionRegistryReg = context - .registerService(RpcProvisionRegistry.class, - broker.getRouter(), emptyProperties); - } - - @Override - public void close() { - - if (dataReg != null) { - dataReg.unregister(); - dataReg = null; - } - if (dataProviderReg != null) { - dataProviderReg.unregister(); - dataProviderReg = null; - } - if (mountReg != null) { - mountReg.unregister(); - mountReg = null; - } - if (mountProviderReg != null) { - mountProviderReg.unregister(); - mountProviderReg = null; - } - if (rpcProvisionRegistryReg != null) { - rpcProvisionRegistryReg.unregister(); - rpcProvisionRegistryReg = null; - } - } - - /** - * @return the dataService - */ - public DataProviderService getDataService() { - return dataService; - } - - /** - * @param dataService - * the dataService to set - */ - public void setDataService(final DataProviderService dataService) { - this.dataService = dataService; - } -} diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java index e4bd0343cf..1af03e5046 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java @@ -7,9 +7,6 @@ */ package org.opendaylight.controller.sal.dom.broker; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.ListenableFuture; - import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -17,22 +14,29 @@ import java.util.concurrent.Future; import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener; import org.opendaylight.controller.sal.core.api.Broker; +import org.opendaylight.controller.sal.core.api.BrokerService; import org.opendaylight.controller.sal.core.api.Consumer; import org.opendaylight.controller.sal.core.api.Provider; +import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation; +import org.opendaylight.controller.sal.core.api.RpcImplementation; +import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; +import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; +import org.opendaylight.controller.sal.core.api.RpcRoutingContext; +import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; +import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter; -import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; -import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; -import org.opendaylight.controller.sal.core.api.RpcImplementation; -import org.opendaylight.controller.sal.core.api.RpcRoutingContext; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.collect.ClassToInstanceMap; +import com.google.common.collect.ImmutableClassToInstanceMap; +import com.google.common.util.concurrent.ListenableFuture; public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { private final static Logger log = LoggerFactory.getLogger(BrokerImpl.class); @@ -43,12 +47,18 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { private final Set providerSessions = Collections .synchronizedSet(new HashSet()); - private BundleContext bundleContext = null; - private AutoCloseable deactivator = null; private RpcRouter router = null; + private final ClassToInstanceMap services; + + public BrokerImpl(final RpcRouter router,final ClassToInstanceMap services) { + this.router = Preconditions.checkNotNull(router, "RPC Router must not be null"); + this.services = ImmutableClassToInstanceMap.copyOf(services); + } + + @Override public ConsumerSession registerConsumer(final Consumer consumer, final BundleContext ctx) { @@ -79,8 +89,9 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { private void checkPredicates(final Provider prov) { Preconditions.checkNotNull(prov, "Provider should not be null."); for (ProviderContextImpl session : providerSessions) { - if (prov.equals(session.getProvider())) + if (prov.equals(session.getProvider())) { throw new IllegalStateException("Provider already registered"); + } } } @@ -88,23 +99,22 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { private void checkPredicates(final Consumer cons) { Preconditions.checkNotNull(cons, "Consumer should not be null."); for (ConsumerContextImpl session : sessions) { - if (cons.equals(session.getConsumer())) + if (cons.equals(session.getConsumer())) { throw new IllegalStateException("Consumer already registered"); + } } } // Private Factory methods private ConsumerContextImpl newSessionFor(final Consumer provider, final BundleContext ctx) { - ConsumerContextImpl ret = new ConsumerContextImpl(provider, ctx); - ret.setBroker(this); + ConsumerContextImpl ret = new ConsumerContextImpl(provider, this); return ret; } private ProviderContextImpl newSessionFor(final Provider provider, final BundleContext ctx) { - ProviderContextImpl ret = new ProviderContextImpl(provider, ctx); - ret.setBroker(this); + ProviderContextImpl ret = new ProviderContextImpl(provider, this); return ret; } @@ -164,21 +174,6 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { return router.invokeRpc(rpc, input); } - /** - * @return the bundleContext - */ - public BundleContext getBundleContext() { - return bundleContext; - } - - /** - * @param bundleContext - * the bundleContext to set - */ - public void setBundleContext(final BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - /** * @return the deactivator */ @@ -208,4 +203,9 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable { public void setRouter(final RpcRouter router) { this.router = router; } + + protected Optional getGlobalService(final Class service) { + return Optional.fromNullable(services.getInstance(service)); + } + } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.java index fa81bc9040..e96b242720 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.java @@ -20,9 +20,9 @@ import org.opendaylight.controller.sal.dom.broker.osgi.ProxyFactory; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.MutableClassToInstanceMap; @@ -30,41 +30,39 @@ class ConsumerContextImpl implements ConsumerSession { private final ClassToInstanceMap instantiatedServices = MutableClassToInstanceMap .create(); - private final BundleContext context; private final Consumer consumer; private BrokerImpl broker = null; @GuardedBy("this") private boolean closed = false; - public ConsumerContextImpl(final Consumer consumer, final BundleContext ctx) { - this.consumer = consumer; - this.context = ctx; + public ConsumerContextImpl(final Consumer provider, final BrokerImpl brokerImpl) { + broker = brokerImpl; + consumer = provider; } @Override public Future> rpc(final QName rpc, final CompositeNode input) { + checkNotClosed(); return broker.invokeRpcAsync(rpc, input); } @Override public T getService(final Class service) { + checkNotClosed(); final T localProxy = instantiatedServices.getInstance(service); if (localProxy != null) { return localProxy; } - final ServiceReference serviceRef = context - .getServiceReference(service); - if (serviceRef == null) { - return null; - } - final T serviceImpl = context.getService(serviceRef); - final T ret = ProxyFactory.createProxy(serviceRef, serviceImpl); - if (ret != null) { + final Optional serviceImpl = broker.getGlobalService(service); + if(serviceImpl.isPresent()) { + final T ret = ProxyFactory.createProxy(null,serviceImpl.get()); instantiatedServices.putInstance(service, ret); + return ret; + } else { + return null; } - return ret; } @Override @@ -83,6 +81,7 @@ class ConsumerContextImpl implements ConsumerSession { } } broker.consumerSessionClosed(this); + broker = null; } @Override @@ -93,22 +92,19 @@ class ConsumerContextImpl implements ConsumerSession { /** * @return the broker */ - public BrokerImpl getBroker() { + protected final BrokerImpl getBrokerChecked() { + checkNotClosed(); return broker; } - /** - * @param broker - * the broker to set - */ - public void setBroker(final BrokerImpl broker) { - this.broker = broker; - } - /** * @return the _consumer */ public Consumer getConsumer() { return consumer; } + + protected final void checkNotClosed() { + Preconditions.checkState(!closed, "Session is closed."); + } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java index 430963a884..60a7e81c4c 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.dom.broker; import static com.google.common.base.Preconditions.checkState; +import com.google.common.annotations.VisibleForTesting; import java.net.URL; import java.util.ArrayList; import java.util.Collections; @@ -50,11 +51,29 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi private ServiceTracker listenerTracker; private BundleTracker>> bundleTracker; private boolean starting = true; + private static GlobalBundleScanningSchemaServiceImpl instance; - public GlobalBundleScanningSchemaServiceImpl(final BundleContext context) { + private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) { this.context = Preconditions.checkNotNull(context); } + public synchronized static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) { + Preconditions.checkState(instance == null); + instance = new GlobalBundleScanningSchemaServiceImpl(ctx); + instance.start(); + return instance; + } + + public synchronized static GlobalBundleScanningSchemaServiceImpl getInstance() { + Preconditions.checkState(instance != null, "Global Instance was not instantiated"); + return instance; + } + + @VisibleForTesting + public static synchronized void destroyInstance() { + instance = null; + } + public BundleContext getContext() { return context; } @@ -96,7 +115,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi } @Override - public ListenerRegistration registerSchemaServiceListener(final SchemaServiceListener listener) { + public synchronized ListenerRegistration registerSchemaServiceListener(final SchemaServiceListener listener) { Optional potentialCtx = contextResolver.getSchemaContext(); if(potentialCtx.isPresent()) { listener.onGlobalContextUpdated(potentialCtx.get()); @@ -116,7 +135,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi } - private void updateContext(final SchemaContext snapshot) { + private synchronized void updateContext(final SchemaContext snapshot) { Object[] services = listenerTracker.getServices(); for (ListenerRegistration listener : listeners) { try { @@ -194,7 +213,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi } @Override - public SchemaServiceListener addingService(final ServiceReference reference) { + public synchronized SchemaServiceListener addingService(final ServiceReference reference) { SchemaServiceListener listener = context.getService(reference); SchemaContext _ctxContext = getGlobalContext(); diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/MountPointImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/MountPointImpl.java index 623bbdb195..e69343d4fe 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/MountPointImpl.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/MountPointImpl.java @@ -54,7 +54,7 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv private SchemaContext schemaContext; - public MountPointImpl(InstanceIdentifier path) { + public MountPointImpl(final InstanceIdentifier path) { this.mountPath = path; rpcs = new SchemaAwareRpcBroker(path.toString(),this); dataReader = new DataBrokerImpl(); @@ -71,49 +71,49 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv } @Override - public void publish(CompositeNode notification) { + public void publish(final CompositeNode notification) { notificationRouter.publish(notification); } @Override - public Registration addNotificationListener(QName notification, NotificationListener listener) { + public Registration addNotificationListener(final QName notification, final NotificationListener listener) { return notificationRouter.addNotificationListener(notification, listener); } @Override - public CompositeNode readConfigurationData(InstanceIdentifier path) { + public CompositeNode readConfigurationData(final InstanceIdentifier path) { return dataReader.readConfigurationData(path); } @Override - public CompositeNode readOperationalData(InstanceIdentifier path) { + public CompositeNode readOperationalData(final InstanceIdentifier path) { return dataReader.readOperationalData(path); } @Override public Registration> registerOperationalReader( - InstanceIdentifier path, DataReader reader) { + final InstanceIdentifier path, final DataReader reader) { return dataReader.registerOperationalReader(path, reader); } @Override public Registration> registerConfigurationReader( - InstanceIdentifier path, DataReader reader) { + final InstanceIdentifier path, final DataReader reader) { return dataReader.registerConfigurationReader(path, reader); } @Override - public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) { + public RoutedRpcRegistration addRoutedRpcImplementation(final QName rpcType, final RpcImplementation implementation) { return rpcs.addRoutedRpcImplementation(rpcType, implementation); } @Override - public void setRoutedRpcDefaultDelegate(RoutedRpcDefaultImplementation defaultImplementation) { - rpcs.setRoutedRpcDefaultDelegate(defaultImplementation); + public void setRoutedRpcDefaultDelegate(final RoutedRpcDefaultImplementation defaultImplementation) { + rpcs.setRoutedRpcDefaultDelegate(defaultImplementation); } - @Override - public RpcRegistration addRpcImplementation(QName rpcType, RpcImplementation implementation) + @Override + public RpcRegistration addRpcImplementation(final QName rpcType, final RpcImplementation implementation) throws IllegalArgumentException { return rpcs.addRpcImplementation(rpcType, implementation); } @@ -124,17 +124,17 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv } @Override - public ListenableFuture> invokeRpc(QName rpc, CompositeNode input) { + public ListenableFuture> invokeRpc(final QName rpc, final CompositeNode input) { return rpcs.invokeRpc(rpc, input); } @Override - public ListenerRegistration addRpcRegistrationListener(RpcRegistrationListener listener) { + public ListenerRegistration addRpcRegistrationListener(final RpcRegistrationListener listener) { return rpcs.addRpcRegistrationListener(listener); } @Override - public ListenableFuture> rpc(QName type, CompositeNode input) { + public ListenableFuture> rpc(final QName type, final CompositeNode input) { return rpcs.invokeRpc( type, input ); } @@ -144,33 +144,33 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv } @Override - public ListenerRegistration registerDataChangeListener(InstanceIdentifier path, - DataChangeListener listener) { + public ListenerRegistration registerDataChangeListener(final InstanceIdentifier path, + final DataChangeListener listener) { return dataReader.registerDataChangeListener(path, listener); } @Override public Registration> registerCommitHandler( - InstanceIdentifier path, DataCommitHandler commitHandler) { + final InstanceIdentifier path, final DataCommitHandler commitHandler) { return dataReader.registerCommitHandler(path, commitHandler); } @Override - public void removeRefresher(DataStoreIdentifier store, DataRefresher refresher) { - // NOOP + public void removeRefresher(final DataStoreIdentifier store, final DataRefresher refresher) { + // NOOP } @Override - public void addRefresher(DataStoreIdentifier store, DataRefresher refresher) { - // NOOP + public void addRefresher(final DataStoreIdentifier store, final DataRefresher refresher) { + // NOOP } @Override - public void addValidator(DataStoreIdentifier store, DataValidator validator) { - // NOOP + public void addValidator(final DataStoreIdentifier store, final DataValidator validator) { + // NOOP } @Override - public void removeValidator(DataStoreIdentifier store, DataValidator validator) { + public void removeValidator(final DataStoreIdentifier store, final DataValidator validator) { // NOOP } @@ -180,24 +180,22 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv } @Override - public void setSchemaContext(SchemaContext schemaContext) { + public void setSchemaContext(final SchemaContext schemaContext) { this.schemaContext = schemaContext; } class ReadWrapper implements DataReader { - - - private InstanceIdentifier shortenPath(InstanceIdentifier path) { + private InstanceIdentifier shortenPath(final InstanceIdentifier path) { InstanceIdentifier ret = null; if(mountPath.contains(path)) { List newArgs = path.getPath().subList(mountPath.getPath().size(), path.getPath().size()); - ret = new InstanceIdentifier(newArgs); + ret = InstanceIdentifier.create(newArgs); } return ret; } @Override - public CompositeNode readConfigurationData(InstanceIdentifier path) { + public CompositeNode readConfigurationData(final InstanceIdentifier path) { InstanceIdentifier newPath = shortenPath(path); if(newPath == null) { return null; @@ -206,7 +204,7 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv } @Override - public CompositeNode readOperationalData(InstanceIdentifier path) { + public CompositeNode readOperationalData(final InstanceIdentifier path) { InstanceIdentifier newPath = shortenPath(path); if(newPath == null) { return null; @@ -217,13 +215,13 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv @Override public ListenerRegistration>> registerCommitHandlerListener( - RegistrationListener> commitHandlerListener) { + final RegistrationListener> commitHandlerListener) { return dataReader.registerCommitHandlerListener(commitHandlerListener); } @Override public > ListenerRegistration registerRouteChangeListener( - L listener) { + final L listener) { return rpcs.registerRouteChangeListener(listener); } } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java index 5e8c0e8253..b8bb279297 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java @@ -18,21 +18,20 @@ import org.opendaylight.controller.sal.core.api.RpcImplementation; import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.common.QName; -import org.osgi.framework.BundleContext; class ProviderContextImpl extends ConsumerContextImpl implements ProviderSession { private final Set registrations = new HashSet<>(); private final Provider provider; - public ProviderContextImpl(final Provider provider, final BundleContext ctx) { - super(null, ctx); + public ProviderContextImpl(final Provider provider, final BrokerImpl broker) { + super(null, broker); this.provider = provider; } @Override public RpcRegistrationWrapper addRpcImplementation(final QName rpcType, final RpcImplementation implementation) throws IllegalArgumentException { - final RpcRegistration origReg = getBroker().getRouter() + final RpcRegistration origReg = getBrokerChecked().getRouter() .addRpcImplementation(rpcType, implementation); final RpcRegistrationWrapper newReg = new RpcRegistrationWrapper( origReg); @@ -56,24 +55,24 @@ class ProviderContextImpl extends ConsumerContextImpl implements ProviderSession final QName rpcType, final RpcImplementation implementation) { throw new UnsupportedOperationException( "TODO: auto-generated method stub"); + } @Override public RoutedRpcRegistration addRoutedRpcImplementation( final QName rpcType, final RpcImplementation implementation) { - throw new UnsupportedOperationException( - "TODO: auto-generated method stub"); + return getBrokerChecked().getRouter().addRoutedRpcImplementation(rpcType, implementation); } @Override public Set getSupportedRpcs() { - return getBroker().getRouter().getSupportedRpcs(); + return getBrokerChecked().getRouter().getSupportedRpcs(); } @Override public ListenerRegistration addRpcRegistrationListener( final RpcRegistrationListener listener) { - return getBroker().getRouter().addRpcRegistrationListener(listener); + return getBrokerChecked().getRouter().addRpcRegistrationListener(listener); } /** diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java index ba9b2b7f55..4b5b86d0da 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java @@ -9,6 +9,8 @@ package org.opendaylight.controller.sal.dom.broker.impl; import static com.google.common.base.Preconditions.checkState; +import com.google.common.collect.Iterables; + import java.net.URI; import java.util.ArrayList; import java.util.Arrays; @@ -32,8 +34,6 @@ import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.Iterables; - public class DataReaderRouter extends AbstractDataReadRouter { private final static Logger LOG = LoggerFactory @@ -46,7 +46,7 @@ AbstractDataReadRouter { @Override protected CompositeNodeTOImpl merge(final InstanceIdentifier path, final Iterable data) { - PathArgument pathArgument = Iterables.getLast(path.getPath(), null); + PathArgument pathArgument = Iterables.getLast(path.getPathArguments(), null); boolean empty = true; QName name = (pathArgument == null ? null : pathArgument.getNodeType()); final ArrayList> nodes = new ArrayList>(); diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java index 1a572d157d..3cd7ed5e13 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java @@ -9,6 +9,11 @@ package org.opendaylight.controller.sal.dom.broker.impl; import static com.google.common.base.Preconditions.checkState; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -40,10 +45,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableSet; - public class SchemaAwareDataStoreAdapter extends AbstractLockableDelegator implements // DataStore, // SchemaContextListener, // @@ -235,7 +236,7 @@ AutoCloseable { public CompositeNode readConfigurationData(final InstanceIdentifier path) { getDelegateReadLock().lock(); try { - if (path.getPath().isEmpty()) { + if (Iterables.isEmpty(path.getPathArguments())) { return null; } QName qname = null; @@ -278,7 +279,7 @@ AutoCloseable { public CompositeNode readOperationalData(final InstanceIdentifier path) { getDelegateReadLock().lock(); try { - if (path.getPath().isEmpty()) { + if (Iterables.isEmpty(path.getPathArguments())) { return null; } QName qname = null; diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java index 853e3e391f..8d33ff7997 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java @@ -14,6 +14,8 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; +import javax.annotation.Nullable; + import org.opendaylight.controller.sal.core.api.BrokerService; import org.opendaylight.yangtools.concepts.Registration; import org.osgi.framework.ServiceReference; @@ -23,9 +25,9 @@ public abstract class AbstractBrokerServiceProxy implem private T delegate; private final ServiceReference reference; - public AbstractBrokerServiceProxy(final ServiceReference ref, final T delegate) { + public AbstractBrokerServiceProxy(final @Nullable ServiceReference ref, final T delegate) { this.delegate = checkNotNull(delegate, "Delegate should not be null."); - this.reference = checkNotNull(ref, "Reference should not be null."); + this.reference = ref; } protected final T getDelegate() { diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java index f893f96d18..113a9c08db 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java @@ -23,7 +23,7 @@ public class SchemaServiceActivator implements BundleActivator { @Override public void start(final BundleContext context) { - schemaService = new GlobalBundleScanningSchemaServiceImpl(context); + schemaService = GlobalBundleScanningSchemaServiceImpl.createInstance(context); schemaService.start(); schemaServiceReg = context.registerService(SchemaService.class, schemaService, new Hashtable()); } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java index 0f8ce1d95d..5adf39142e 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java @@ -9,6 +9,9 @@ package org.opendaylight.controller.sal.dom.broker.util; import static com.google.common.base.Preconditions.checkArgument; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -29,9 +32,6 @@ import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; - public class YangDataOperations { public static CompositeNode merge(final DataSchemaNode schema, @@ -84,10 +84,10 @@ public class YangDataOperations { } @SuppressWarnings({ "unchecked", "rawtypes" }) final Map, CompositeNode> originalMap = YangDataUtils - .toIndexMap((List) original, node.getKeyDefinition()); + .toIndexMap((List) original, node.getKeyDefinition()); @SuppressWarnings({ "unchecked", "rawtypes" }) final Map, CompositeNode> modifiedMap = YangDataUtils - .toIndexMap((List) modified, node.getKeyDefinition()); + .toIndexMap((List) modified, node.getKeyDefinition()); final List> mergedNodes = new ArrayList>( original.size() + modified.size()); @@ -140,7 +140,7 @@ public class YangDataOperations { modified.getNodeType())); final List> mergedChildNodes = new ArrayList>(stored - .getChildren().size() + modified.getChildren().size()); + .getValue().size() + modified.getValue().size()); final Set toProcess = new HashSet(stored.keySet()); toProcess.addAll(modified.keySet()); diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java index 306cd34a69..29392dc7b3 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java @@ -10,6 +10,9 @@ package org.opendaylight.controller.sal.dom.broker.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; +import com.google.common.base.Function; +import com.google.common.collect.FluentIterable; + import java.util.Iterator; import java.util.List; import java.util.Set; @@ -34,9 +37,6 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; import org.opendaylight.yangtools.yang.model.api.UsesNode; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; - public final class YangSchemaUtils { private static final Function QNAME_FROM_PATH_ARGUMENT = new Function(){ @@ -57,7 +57,7 @@ public final class YangSchemaUtils { public static DataSchemaNode getSchemaNode(final SchemaContext schema,final InstanceIdentifier path) { checkArgument(schema != null,"YANG Schema must not be null."); checkArgument(path != null,"Path must not be null."); - return getSchemaNode(schema, FluentIterable.from(path.getPath()).transform(QNAME_FROM_PATH_ARGUMENT)); + return getSchemaNode(schema, FluentIterable.from(path.getPathArguments()).transform(QNAME_FROM_PATH_ARGUMENT)); } public static DataSchemaNode getSchemaNode(final SchemaContext schema,final Iterable path) { diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang b/opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang index 82897b0198..a0ee5c50c9 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang +++ b/opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang @@ -55,7 +55,7 @@ module opendaylight-sal-dom-broker-impl { } } } - + container async-data-broker { uses config:service-ref { refine type { @@ -63,7 +63,15 @@ module opendaylight-sal-dom-broker-impl { config:required-identity sal:dom-async-data-broker; } } - + } + + container root-schema-service { + uses config:service-ref { + refine type { + mandatory false; + config:required-identity sal:schema-service; + } + } } } } diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java b/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java index e6221f6920..9d04a1b6ed 100644 --- a/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java +++ b/opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java @@ -9,6 +9,19 @@ package org.opendaylight.controller.md.sal.dom.store.impl.tree; import com.google.common.base.Optional; import com.google.common.base.Preconditions; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.annotation.concurrent.GuardedBy; + import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration; @@ -21,17 +34,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.concurrent.GuardedBy; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - /** * A set of listeners organized as a tree by node to which they listen. This class * allows for efficient lookup of listeners when we walk the DataTreeCandidate. @@ -70,7 +72,7 @@ public final class ListenerTree { try { Node walkNode = rootNode; - for (final PathArgument arg : path.getPath()) { + for (final PathArgument arg : path.getPathArguments()) { walkNode = walkNode.ensureChild(arg); } diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java index 2909baccdb..3535c96c80 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java @@ -74,7 +74,7 @@ public final class NetconfDeviceDataReader implements DataReader findNode(final CompositeNode node, final InstanceIdentifier identifier) { Node current = node; - for (final InstanceIdentifier.PathArgument arg : identifier.getPath()) { + for (final InstanceIdentifier.PathArgument arg : identifier.getPathArguments()) { if (current instanceof SimpleNode) { return null; } else if (current instanceof CompositeNode) { diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java index 1a3b108f8b..1737b8234a 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java @@ -21,13 +21,16 @@ import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessag import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; + import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; + import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction; import org.opendaylight.controller.md.sal.common.api.data.DataModification; import org.opendaylight.controller.sal.common.util.RpcErrors; @@ -108,7 +111,7 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact } } - private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, Optional defaultOperation) { + private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional defaultOperation) { final CompositeNodeBuilder ret = ImmutableCompositeNode.builder(); // Target @@ -133,8 +136,8 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact } private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional operation, - final Optional lastChildOverride) { - Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath); + final Optional lastChildOverride) { + Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath); List reversedPath = Lists.reverse(dataPath.getPath()); diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java index ee6daa1e3d..0ea3d6a35a 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java @@ -7,6 +7,14 @@ */ package org.opendaylight.controller.sal.connect.netconf.util; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + import java.net.URI; import java.util.ArrayList; import java.util.Collections; @@ -36,13 +44,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.w3c.dom.Document; import org.w3c.dom.Element; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - public class NetconfMessageTransformUtil { private NetconfMessageTransformUtil() { @@ -76,7 +77,7 @@ public class NetconfMessageTransformUtil { public static Node toFilterStructure(final InstanceIdentifier identifier) { Node previous = null; - if (identifier.getPath().isEmpty()) { + if (Iterables.isEmpty(identifier.getPathArguments())) { return null; } @@ -103,15 +104,15 @@ public class NetconfMessageTransformUtil { } public static void checkValidReply(final NetconfMessage input, final NetconfMessage output) - throws NetconfDocumentedException { + throws NetconfDocumentedException { final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id"); final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id"); if(inputMsgId.equals(outputMsgId) == false) { Map errorInfo = ImmutableMap.builder() - .put( "actual-message-id", outputMsgId ) - .put( "expected-message-id", inputMsgId ) - .build(); + .put( "actual-message-id", outputMsgId ) + .put( "expected-message-id", inputMsgId ) + .build(); throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"", null, NetconfDocumentedException.ErrorType.protocol, @@ -126,7 +127,7 @@ public class NetconfMessageTransformUtil { } } - public static RpcError toRpcError( NetconfDocumentedException ex ) + public static RpcError toRpcError( final NetconfDocumentedException ex ) { StringBuilder infoBuilder = new StringBuilder(); Map errorInfo = ex.getErrorInfo(); @@ -134,44 +135,45 @@ public class NetconfMessageTransformUtil { { for( Entry e: errorInfo.entrySet() ) { infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() ) - .append( "' ); + .append( "' ); } } return RpcErrors.getRpcError( null, ex.getErrorTag().getTagValue(), infoBuilder.toString(), - toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(), - toRpcErrorType( ex.getErrorType() ), ex.getCause() ); + toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(), + toRpcErrorType( ex.getErrorType() ), ex.getCause() ); } - private static ErrorSeverity toRpcErrorSeverity( NetconfDocumentedException.ErrorSeverity severity ) { + private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) { switch( severity ) { - case warning: - return RpcError.ErrorSeverity.WARNING; - default: - return RpcError.ErrorSeverity.ERROR; + case warning: + return RpcError.ErrorSeverity.WARNING; + default: + return RpcError.ErrorSeverity.ERROR; } } - private static RpcError.ErrorType toRpcErrorType( NetconfDocumentedException.ErrorType type ) + private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type ) { switch( type ) { - case protocol: - return RpcError.ErrorType.PROTOCOL; - case rpc: - return RpcError.ErrorType.RPC; - case transport: - return RpcError.ErrorType.TRANSPORT; - default: - return RpcError.ErrorType.APPLICATION; + case protocol: + return RpcError.ErrorType.PROTOCOL; + case rpc: + return RpcError.ErrorType.RPC; + case transport: + return RpcError.ErrorType.TRANSPORT; + default: + return RpcError.ErrorType.APPLICATION; } } public static CompositeNode flattenInput(final CompositeNode node) { final QName inputQName = QName.create(node.getNodeType(), "input"); final CompositeNode input = node.getFirstCompositeByName(inputQName); - if (input == null) + if (input == null) { return node; + } if (input instanceof CompositeNode) { final List> nodes = ImmutableList.> builder() // diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java index 696bf71535..85b4b2dee0 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java @@ -11,13 +11,16 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; import com.google.gson.stream.JsonWriter; + import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.activation.UnsupportedDataTypeException; + import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; @@ -50,16 +53,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class JsonMapper { + private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class); + private final MountInstance mountPoint; - private MountInstance mountPoint; - private final Logger logger = LoggerFactory.getLogger(JsonMapper.class); + public JsonMapper(final MountInstance mountPoint) { + this.mountPoint = mountPoint; + } - public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final MountInstance mountPoint) + public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema) throws IOException { Preconditions.checkNotNull(writer); Preconditions.checkNotNull(data); Preconditions.checkNotNull(schema); - this.mountPoint = mountPoint; writer.beginObject(); @@ -82,73 +87,68 @@ class JsonMapper { final Set foundLists = new HashSet<>(); Set parentSchemaChildNodes = parentSchema == null ? - Collections.emptySet() : parentSchema.getChildNodes(); + Collections.emptySet() : parentSchema.getChildNodes(); - for (Node child : parent.getValue()) { - DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes); + for (Node child : parent.getValue()) { + DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes); - if (childSchema == null) { - // Node may not conform to schema or allows "anyxml" - we'll process it. + if (childSchema == null) { + // Node may not conform to schema or allows "anyxml" - we'll process it. - logger.debug( "No schema found for data node \"" + child.getNodeType() ); + LOG.debug("No schema found for data node \"{}\"", child.getNodeType()); - if( !foundLists.contains( child.getNodeType() ) ) { - handleNoSchemaFound( writer, child, parent ); + if( !foundLists.contains( child.getNodeType() ) ) { + handleNoSchemaFound( writer, child, parent ); - // Since we don't have a schema, we don't know which nodes are supposed to be - // lists so treat every one as a potential list to avoid outputting duplicates. + // Since we don't have a schema, we don't know which nodes are supposed to be + // lists so treat every one as a potential list to avoid outputting duplicates. - foundLists.add( child.getNodeType() ); - } - } - else if (childSchema instanceof ContainerSchemaNode) { - Preconditions.checkState(child instanceof CompositeNode, - "Data representation of Container should be CompositeNode - " + child.getNodeType()); - writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema); - } else if (childSchema instanceof ListSchemaNode) { - if (!foundLists.contains( child.getNodeType() ) ) { - Preconditions.checkState(child instanceof CompositeNode, - "Data representation of List should be CompositeNode - " + child.getNodeType()); - foundLists.add( child.getNodeType() ); - writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema); - } - } else if (childSchema instanceof LeafListSchemaNode) { - if (!foundLists.contains( child.getNodeType() ) ) { - Preconditions.checkState(child instanceof SimpleNode, - "Data representation of LeafList should be SimpleNode - " + child.getNodeType()); - foundLists.add( child.getNodeType() ); - writeLeafList(writer, parent, (SimpleNode) child, (LeafListSchemaNode) childSchema); - } - } else if (childSchema instanceof LeafSchemaNode) { - Preconditions.checkState(child instanceof SimpleNode, - "Data representation of LeafList should be SimpleNode - " + child.getNodeType()); - writeLeaf(writer, (SimpleNode) child, (LeafSchemaNode) childSchema); - } else if (childSchema instanceof AnyXmlSchemaNode) { - if( child instanceof CompositeNode ) { - writeContainer(writer, (CompositeNode) child, null); - } - else { - handleNoSchemaFound( writer, child, parent ); + foundLists.add( child.getNodeType() ); + } + } + else if (childSchema instanceof ContainerSchemaNode) { + Preconditions.checkState(child instanceof CompositeNode, + "Data representation of Container should be CompositeNode - %s", child.getNodeType()); + writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema); + } else if (childSchema instanceof ListSchemaNode) { + if (!foundLists.contains( child.getNodeType() ) ) { + Preconditions.checkState(child instanceof CompositeNode, + "Data representation of List should be CompositeNode - %s", child.getNodeType()); + foundLists.add( child.getNodeType() ); + writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema); + } + } else if (childSchema instanceof LeafListSchemaNode) { + if (!foundLists.contains( child.getNodeType() ) ) { + Preconditions.checkState(child instanceof SimpleNode, + "Data representation of LeafList should be SimpleNode - %s", child.getNodeType()); + foundLists.add( child.getNodeType() ); + writeLeafList(writer, parent, (SimpleNode) child, (LeafListSchemaNode) childSchema); + } + } else if (childSchema instanceof LeafSchemaNode) { + Preconditions.checkState(child instanceof SimpleNode, + "Data representation of LeafList should be SimpleNode - %s", child.getNodeType()); + writeLeaf(writer, (SimpleNode) child, (LeafSchemaNode) childSchema); + } else if (childSchema instanceof AnyXmlSchemaNode) { + if( child instanceof CompositeNode ) { + writeContainer(writer, (CompositeNode) child, null); + } + else { + handleNoSchemaFound( writer, child, parent ); + } + } else { + throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, " + + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet."); + } } - } else { - throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, " - + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet."); - } - } } - private void writeValue( final JsonWriter writer, Object value ) throws IOException { - if( value != null ) { - writer.value( String.valueOf( value ) ); - } - else { - writer.value( "" ); - } + private static void writeValue(final JsonWriter writer, final Object value) throws IOException { + writer.value(value == null ? "" : String.valueOf(value)); } private void handleNoSchemaFound( final JsonWriter writer, final Node node, - final CompositeNode parent ) throws IOException { + final CompositeNode parent ) throws IOException { if( node instanceof SimpleNode ) { List> nodeLeafList = parent.getSimpleNodesByName( node.getNodeType() ); if( nodeLeafList.size() == 1 ) { @@ -166,7 +166,7 @@ class JsonMapper { } } else { // CompositeNode Preconditions.checkState( node instanceof CompositeNode, - "Data representation of Container should be CompositeNode - " + node.getNodeType() ); + "Data representation of Container should be CompositeNode - %s", node.getNodeType()); List nodeList = parent.getCompositesByName( node.getNodeType() ); if( nodeList.size() == 1 ) { @@ -178,11 +178,12 @@ class JsonMapper { } } - private DataSchemaNode findFirstSchemaForNode(final Node node, final Set dataSchemaNode) { + private static DataSchemaNode findFirstSchemaForNode(final Node node, final Set dataSchemaNode) { for (DataSchemaNode dsn : dataSchemaNode) { if (node.getNodeType().equals(dsn.getQName())) { return dsn; - } else if (dsn instanceof ChoiceNode) { + } + if (dsn instanceof ChoiceNode) { for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) { DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes()); if (foundDsn != null) { @@ -245,8 +246,8 @@ class JsonMapper { TypeDefinition baseType = RestUtil.resolveBaseTypeFrom(type); if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) { - logger.debug("While generationg JSON output null value was found for type " - + baseType.getClass().getSimpleName() + "."); + LOG.debug("While generationg JSON output null value was found for type {}.", + baseType.getClass().getSimpleName()); } if (baseType instanceof IdentityrefTypeDefinition) { @@ -291,25 +292,24 @@ class JsonMapper { } } - private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException { + private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException { StringBuilder result = new StringBuilder(); for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) { - result.append("/"); + result.append('/'); writeModuleNameAndIdentifier(result, identityValue); if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) { for (Predicate predicate : identityValue.getPredicates()) { IdentityValue identityValuePredicate = predicate.getName(); - result.append("["); + result.append('['); if (identityValuePredicate == null) { - result.append("."); + result.append('.'); } else { writeModuleNameAndIdentifier(result, identityValuePredicate); } result.append("='"); result.append(predicate.getValue()); - result.append("'"); - result.append("]"); + result.append("']"); } } } @@ -317,21 +317,22 @@ class JsonMapper { writer.value(result.toString()); } - private void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) { + private static void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) { String moduleName = ControllerContext.getInstance().findModuleNameByNamespace( URI.create(identityValue.getNamespace())); if (moduleName != null && !moduleName.isEmpty()) { result.append(moduleName); - result.append(":"); + result.append(':'); } result.append(identityValue.getValue()); } - private void writeStringRepresentation(final JsonWriter writer, final SimpleNode node, final TypeDefinition baseType, + private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode node, final TypeDefinition baseType, final Class requiredType) throws IOException { Object value = node.getValue(); - logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName() - + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass()); + LOG.debug("Value of {}:{} is not instance of {} but is {}", + baseType.getQName().getNamespace(), baseType.getQName().getLocalName(), + requiredType.getClass(), node.getValue().getClass()); if (value == null) { writer.value(""); } else { @@ -358,7 +359,7 @@ class JsonMapper { if (moduleName != null) { nameForOutput = moduleName.toString(); } else { - logger.info("Module '{}' was not found in schema from mount point", schema.getQName()); + LOG.info("Module '{}' was not found in schema from mount point", schema.getQName()); } } writer.name(nameForOutput); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java index 1f7b061e92..e945540618 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java @@ -7,9 +7,17 @@ */ package org.opendaylight.controller.sal.rest.impl; +import com.google.common.base.Splitter; +import com.google.common.collect.Iterators; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; + import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; +import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; @@ -18,21 +26,22 @@ import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import com.google.common.collect.Lists; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; +final class JsonReader { + private static final Logger LOG = LoggerFactory.getLogger(JsonReader.class); + private static final Splitter COLON_SPLITTER = Splitter.on(':'); + + private JsonReader() { -class JsonReader { + } - public CompositeNodeWrapper read(InputStream entityStream) throws UnsupportedFormatException { + public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException { JsonParser parser = new JsonParser(); JsonElement rootElement = parser.parse(new InputStreamReader(entityStream)); - if( rootElement.isJsonNull() ) - { + if (rootElement.isJsonNull()) { //no content, so return null to indicate no input return null; } @@ -44,29 +53,31 @@ class JsonReader { Set> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet(); if (entrySetsOfRootJsonObject.size() != 1) { throw new UnsupportedFormatException("Json Object should contain one element"); - } else { - Entry childEntry = Lists.newArrayList(entrySetsOfRootJsonObject).get(0); - String firstElementName = childEntry.getKey(); - JsonElement firstElementType = childEntry.getValue(); - if (firstElementType.isJsonObject()) { // container in yang - return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject()); - } - if (firstElementType.isJsonArray()) { // list in yang - if (firstElementType.getAsJsonArray().size() == 1) { - JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0); - if (firstElementInArray.isJsonObject()) { - return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject()); - } - throw new UnsupportedFormatException( - "Array as the first element in Json Object can have only Object element"); + } + + Entry childEntry = entrySetsOfRootJsonObject.iterator().next(); + String firstElementName = childEntry.getKey(); + JsonElement firstElementType = childEntry.getValue(); + if (firstElementType.isJsonObject()) { + // container in yang + return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject()); + } + if (firstElementType.isJsonArray()) { + // list in yang + if (firstElementType.getAsJsonArray().size() == 1) { + JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0); + if (firstElementInArray.isJsonObject()) { + return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject()); } + throw new UnsupportedFormatException( + "Array as the first element in Json Object can have only Object element"); } - throw new UnsupportedFormatException( - "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."); } + throw new UnsupportedFormatException( + "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."); } - private CompositeNodeWrapper createStructureWithRoot(String rootObjectName, JsonObject rootObject) { + private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) { CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName), getLocalNameFor(rootObjectName)); for (Entry childOfFirstNode : rootObject.entrySet()) { @@ -75,7 +86,7 @@ class JsonReader { return firstNode; } - private void addChildToParent(String childName, JsonElement childType, CompositeNodeWrapper parent) { + private static void addChildToParent(final String childName, final JsonElement childType, final CompositeNodeWrapper parent) { if (childType.isJsonObject()) { CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)); parent.addValue(child); @@ -85,7 +96,6 @@ class JsonReader { } else if (childType.isJsonArray()) { if (childType.getAsJsonArray().size() == 1 && childType.getAsJsonArray().get(0).isJsonNull()) { parent.addValue(new EmptyNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName))); - } else { for (JsonElement childOfChildType : childType.getAsJsonArray()) { addChildToParent(childName, childOfChildType, parent); @@ -96,35 +106,42 @@ class JsonReader { String value = childPrimitive.getAsString().trim(); parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName), resolveValueOfElement(value))); + } else { + LOG.debug("Ignoring unhandled child type {}", childType); } } - private URI getNamespaceFor(String jsonElementName) { - String[] moduleNameAndLocalName = jsonElementName.split(":"); - // it is not "moduleName:localName" - if (moduleNameAndLocalName.length != 2) { - return null; + private static URI getNamespaceFor(final String jsonElementName) { + final Iterator it = COLON_SPLITTER.split(jsonElementName).iterator(); + + // The string needs to me in form "moduleName:localName" + if (it.hasNext()) { + final String maybeURI = it.next(); + if (Iterators.size(it) == 1) { + return URI.create(maybeURI); + } } - return URI.create(moduleNameAndLocalName[0]); + + return null; } - private String getLocalNameFor(String jsonElementName) { - String[] moduleNameAndLocalName = jsonElementName.split(":"); - // it is not "moduleName:localName" - if (moduleNameAndLocalName.length != 2) { - return jsonElementName; - } - return moduleNameAndLocalName[1]; + private static String getLocalNameFor(final String jsonElementName) { + final Iterator it = COLON_SPLITTER.split(jsonElementName).iterator(); + + // The string needs to me in form "moduleName:localName" + final String ret = Iterators.get(it, 1, null); + return ret != null && !it.hasNext() ? ret : jsonElementName; } - private Object resolveValueOfElement(String value) { + private static Object resolveValueOfElement(final String value) { // it could be instance-identifier Built-In Type - if (value.startsWith("/")) { + if (!value.isEmpty() && value.charAt(0) == '/') { IdentityValuesDTO resolvedValue = RestUtil.asInstanceIdentifier(value, new PrefixMapingFromJson()); if (resolvedValue != null) { return resolvedValue; } } + // it could be identityref Built-In Type URI namespace = getNamespaceFor(value); if (namespace != null) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java index 856e09fabd..9e69665405 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java @@ -30,29 +30,28 @@ import org.slf4j.LoggerFactory; @Provider @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON, - MediaType.APPLICATION_JSON }) + MediaType.APPLICATION_JSON }) public enum JsonToCompositeNodeProvider implements MessageBodyReader { INSTANCE; private final static Logger LOG = LoggerFactory.getLogger( JsonToCompositeNodeProvider.class ); @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public boolean isReadable(final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return true; } @Override - public CompositeNode readFrom(Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - JsonReader jsonReader = new JsonReader(); + public CompositeNode readFrom(final Class type, final Type genericType, final Annotation[] annotations, + final MediaType mediaType, final MultivaluedMap httpHeaders, final InputStream entityStream) + throws IOException, WebApplicationException { try { - return jsonReader.read(entityStream); + return JsonReader.read(entityStream); } catch (Exception e) { - LOG.debug( "Error parsing json input", e ); + LOG.debug( "Error parsing json input", e); throw new RestconfDocumentedException( - "Error parsing input: " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE ); + "Error parsing input: " + e.getMessage(), + ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java index 290d976b28..cd263d3c55 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java @@ -21,11 +21,13 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition; public final class RestUtil { + // FIXME: BUG-1275: this is code duplicates data.impl.codec + public static final String SQUOTE = "'"; public static final String DQUOTE = "\""; private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]"); - public final static TypeDefinition resolveBaseTypeFrom(TypeDefinition type) { + public final static TypeDefinition resolveBaseTypeFrom(final TypeDefinition type) { TypeDefinition superType = type; while (superType.getBaseType() != null) { superType = superType.getBaseType(); @@ -33,7 +35,7 @@ public final class RestUtil { return superType; } - public static IdentityValuesDTO asInstanceIdentifier(String value, PrefixesMaping prefixMap) { + public static IdentityValuesDTO asInstanceIdentifier(final String value, final PrefixesMaping prefixMap) { String valueTrimmed = value.trim(); if (!valueTrimmed.startsWith("/")) { return null; @@ -63,12 +65,12 @@ public final class RestUtil { return identityValuesDTO.getValuesWithNamespaces().isEmpty() ? null : identityValuesDTO; } - private static String getIdAndPrefixAsStr(String pathPart) { + private static String getIdAndPrefixAsStr(final String pathPart) { int predicateStartIndex = pathPart.indexOf("["); return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex); } - private static IdentityValue toIdentity(String xPathPart, PrefixesMaping prefixMap) { + private static IdentityValue toIdentity(final String xPathPart, final PrefixesMaping prefixMap) { String xPathPartTrimmed = xPathPart.trim(); if (xPathPartTrimmed.isEmpty()) { return null; @@ -87,7 +89,7 @@ public final class RestUtil { return new IdentityValue(namespace, identifier, namespace.equals(prefix) ? null : prefix); } - private static List toPredicates(String predicatesStr, PrefixesMaping prefixMap) { + private static List toPredicates(final String predicatesStr, final PrefixesMaping prefixMap) { List result = new ArrayList<>(); List predicates = new ArrayList<>(); Matcher matcher = PREDICATE_PATTERN.matcher(predicatesStr); @@ -116,7 +118,7 @@ public final class RestUtil { return result; } - private static String toPredicateValue(String predicatedValue) { + private static String toPredicateValue(final String predicatedValue) { String predicatedValueTrimmed = predicatedValue.trim(); if ((predicatedValueTrimmed.startsWith(DQUOTE) || predicatedValueTrimmed.startsWith(SQUOTE)) && (predicatedValueTrimmed.endsWith(DQUOTE) || predicatedValueTrimmed.endsWith(SQUOTE))) { @@ -132,12 +134,12 @@ public final class RestUtil { public static class PrefixMapingFromXml implements PrefixesMaping { StartElement startElement = null; - public PrefixMapingFromXml(StartElement startElement) { + public PrefixMapingFromXml(final StartElement startElement) { this.startElement = startElement; } @Override - public String getNamespace(String prefix) { + public String getNamespace(final String prefix) { return startElement.getNamespaceContext().getNamespaceURI(prefix); } } @@ -145,7 +147,7 @@ public final class RestUtil { public static class PrefixMapingFromJson implements PrefixesMaping { @Override - public String getNamespace(String prefix) { + public String getNamespace(final String prefix) { return prefix; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java index 5f6909cea8..0854ca7167 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java @@ -17,6 +17,11 @@ import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ER import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ERROR_TYPE_QNAME; import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.NAMESPACE; +import com.google.common.base.Charsets; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.gson.stream.JsonWriter; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; @@ -57,10 +62,6 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.gson.stream.JsonWriter; - /** * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by * resource implementations and translates appropriately to restconf error response as defined in @@ -139,20 +140,19 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper { INSTANCE; @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public boolean isWriteable(final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return type.equals( StructuredData.class ); } @Override - public long getSize(StructuredData t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public long getSize(final StructuredData t, final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return -1; } @Override - public void writeTo(StructuredData t, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException, WebApplicationException { + public void writeTo(final StructuredData t, final Class type, final Type genericType, final Annotation[] annotations, + final MediaType mediaType, final MultivaluedMap httpHeaders, final OutputStream entityStream) + throws IOException, WebApplicationException { CompositeNode data = t.getData(); if (data == null) { throw new RestconfDocumentedException(Response.Status.NOT_FOUND); } - JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8")); + JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, Charsets.UTF_8)); writer.setIndent(" "); - JsonMapper jsonMapper = new JsonMapper(); - jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema(), t.getMountPoint()); + JsonMapper jsonMapper = new JsonMapper(t.getMountPoint()); + jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema()); writer.flush(); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java index bcb3c422ff..e5a56cf475 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java @@ -21,6 +21,7 @@ import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; @@ -40,46 +41,68 @@ import org.w3c.dom.Document; @Provider @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML, - Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) + Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public enum StructuredDataToXmlProvider implements MessageBodyWriter { INSTANCE; - private final static Logger logger = LoggerFactory.getLogger(StructuredDataToXmlProvider.class); + private static final Logger LOG = LoggerFactory.getLogger(StructuredDataToXmlProvider.class); + private static final TransformerFactory FACTORY = TransformerFactory.newInstance(); + private static final ThreadLocal TRANSFORMER = new ThreadLocal() { + @Override + protected Transformer initialValue() { + final Transformer ret; + try { + ret = FACTORY.newTransformer(); + } catch (TransformerConfigurationException e) { + LOG.error("Failed to instantiate XML transformer", e); + throw new IllegalStateException("XML encoding currently unavailable", e); + } + + ret.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + ret.setOutputProperty(OutputKeys.METHOD, "xml"); + ret.setOutputProperty(OutputKeys.INDENT, "yes"); + ret.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + ret.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + + return ret; + } + }; @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public boolean isWriteable(final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return type.equals( StructuredData.class ); } @Override - public long getSize(StructuredData t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public long getSize(final StructuredData t, final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return -1; } @Override - public void writeTo(StructuredData t, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException, WebApplicationException { + public void writeTo(final StructuredData t, final Class type, final Type genericType, final Annotation[] annotations, + final MediaType mediaType, final MultivaluedMap httpHeaders, final OutputStream entityStream) + throws IOException, WebApplicationException { CompositeNode data = t.getData(); if (data == null) { throw new RestconfDocumentedException(Response.Status.NOT_FOUND); } - XmlMapper xmlMapper = new XmlMapper(); - Document domTree = xmlMapper.write(data, (DataNodeContainer) t.getSchema()); + final Transformer trans; + try { + trans = TRANSFORMER.get(); + } catch (RuntimeException e) { + throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, + ErrorTag.OPERATION_FAILED); + } + + // FIXME: BUG-1281: eliminate the intermediate Document + final Document domTree = new XmlMapper().write(data, (DataNodeContainer) t.getSchema()); try { - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - transformer.transform(new DOMSource(domTree), new StreamResult(entityStream)); + trans.transform(new DOMSource(domTree), new StreamResult(entityStream)); } catch (TransformerException e) { - logger.error("Error during translation of Document to OutputStream", e); - throw new RestconfDocumentedException( e.getMessage(), ErrorType.TRANSPORT, - ErrorTag.OPERATION_FAILED ); + LOG.error("Error during translation of Document to OutputStream", e); + throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, + ErrorTag.OPERATION_FAILED); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java index 96ad528a0d..69b975dab7 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java @@ -7,6 +7,8 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Preconditions; + import java.net.URI; import java.util.ArrayList; import java.util.Collection; @@ -23,8 +25,6 @@ import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; -import com.google.common.base.Preconditions; - public final class CompositeNodeWrapper implements NodeWrapper, CompositeNode { private MutableCompositeNode compositeNode; @@ -104,7 +104,7 @@ public final class CompositeNodeWrapper implements NodeWrapper, C name = new QName(namespace, localName); } - List> nodeValues = new ArrayList<>(); + List> nodeValues = new ArrayList<>(values.size()); for (NodeWrapper nodeWrapper : values) { nodeValues.add(nodeWrapper.unwrap()); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java index 6330c0a479..85c8e59539 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java @@ -7,6 +7,18 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.base.Predicate; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; +import com.google.common.collect.BiMap; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Iterables; + import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; @@ -55,19 +67,6 @@ import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.BiMap; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - public class ControllerContext implements SchemaContextListener { private final static Logger LOG = LoggerFactory.getLogger( ControllerContext.class ); @@ -83,6 +82,10 @@ public class ControllerContext implements SchemaContextListener { private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1"; + private static final Splitter SLASH_SPLITTER = Splitter.on('/'); + + private static final Splitter COLON_SPLITTER = Splitter.on(':'); + private final BiMap uriToModuleName = HashBiMap. create(); private final Map moduleNameToUri = uriToModuleName.inverse(); @@ -129,10 +132,8 @@ public class ControllerContext implements SchemaContextListener { final boolean toMountPointIdentifier ) { this.checkPreconditions(); - Iterable split = Splitter.on( "/" ).split( restconfInstance ); - final ArrayList encodedPathArgs = Lists. newArrayList( split ); - final List pathArgs = this.urlPathArgsDecode( encodedPathArgs ); - this.omitFirstAndLastEmptyString( pathArgs ); + final List pathArgs = urlPathArgsDecode( SLASH_SPLITTER.split( restconfInstance ) ); + omitFirstAndLastEmptyString( pathArgs ); if( pathArgs.isEmpty() ) { return null; } @@ -158,7 +159,7 @@ public class ControllerContext implements SchemaContextListener { return iiWithSchemaNode; } - private List omitFirstAndLastEmptyString( final List list ) { + private static List omitFirstAndLastEmptyString( final List list ) { if( list.isEmpty() ) { return list; } @@ -256,7 +257,7 @@ public class ControllerContext implements SchemaContextListener { public DataNodeContainer getDataNodeContainerFor( final InstanceIdentifier path ) { this.checkPreconditions(); - final List elements = path.getPath(); + final Iterable elements = path.getPathArguments(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); final Module initialModule = globalSchema.findModuleByNamespaceAndRevision( @@ -277,7 +278,7 @@ public class ControllerContext implements SchemaContextListener { public String toFullRestconfIdentifier( final InstanceIdentifier path ) { this.checkPreconditions(); - final List elements = path.getPath(); + final Iterable elements = path.getPathArguments(); final StringBuilder builder = new StringBuilder(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); @@ -562,7 +563,7 @@ public class ControllerContext implements SchemaContextListener { } String head = strings.iterator().next(); - final String nodeName = this.toNodeName( head ); + final String nodeName = toNodeName( head ); final String moduleName = ControllerContext.toModuleName( head ); DataSchemaNode targetNode = null; @@ -805,8 +806,8 @@ public class ControllerContext implements SchemaContextListener { public boolean isInstantiatedDataSchema( final DataSchemaNode node ) { return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode || - node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || - node instanceof AnyXmlSchemaNode; + node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || + node instanceof AnyXmlSchemaNode; } private void addKeyValue( final HashMap map, final DataSchemaNode node, @@ -839,20 +840,20 @@ public class ControllerContext implements SchemaContextListener { private static String toModuleName( final String str ) { Preconditions. checkNotNull( str ); - if( str.contains( ":" ) ) { - final String[] args = str.split( ":" ); - if( args.length == 2 ) { - return args[0]; + if( str.indexOf( ':' ) != -1 ) { + final Iterable args = COLON_SPLITTER.split( str ); + if( Iterables.size( args ) == 2 ) { + return args.iterator().next(); } } return null; } - private String toNodeName( final String str ) { - if( str.contains( ":" ) ) { - final String[] args = str.split( ":" ); - if( args.length == 2 ) { - return args[1]; + private static String toNodeName( final String str ) { + if( str.indexOf( ':' ) != -1 ) { + final Iterable args = COLON_SPLITTER.split( str ); + if( Iterables.size( args ) == 2 ) { + return Iterables.get( args, 1 ); } } return str; @@ -860,7 +861,7 @@ public class ControllerContext implements SchemaContextListener { private QName toQName( final String name ) { final String module = toModuleName( name ); - final String node = this.toNodeName( name ); + final String node = toNodeName( name ); Set modules = globalSchema.getModules(); final Comparator comparator = new Comparator() { @@ -916,7 +917,7 @@ public class ControllerContext implements SchemaContextListener { } } - public List urlPathArgsDecode( final List strings ) { + public static List urlPathArgsDecode( final Iterable strings ) { try { List decodedPathArgs = new ArrayList(); for( final String pathArg : strings ) { @@ -998,7 +999,7 @@ public class ControllerContext implements SchemaContextListener { try { builder.append( this.toUriString( keyValues.get( key ) ) ); } catch( UnsupportedEncodingException e ) { - LOG.error( "Error parsing URI: " + keyValues.get( key ), e ); + LOG.error( "Error parsing URI: {}", keyValues.get( key ), e ); return null; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java index 934d4434c3..f93a0aea70 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java @@ -7,6 +7,8 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Preconditions; + import java.net.URI; import java.util.Collections; @@ -15,8 +17,6 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; -import com.google.common.base.Preconditions; - public final class EmptyNodeWrapper implements NodeWrapper>, Node { private Node unwrapped; @@ -31,17 +31,17 @@ public final class EmptyNodeWrapper implements NodeWrapper>, Node return composite; } - public void setComposite(boolean composite) { + public void setComposite(final boolean composite) { this.composite = composite; } - public EmptyNodeWrapper(URI namespace, String localName) { + public EmptyNodeWrapper(final URI namespace, final String localName) { this.localName = Preconditions.checkNotNull(localName); this.namespace = namespace; } @Override - public void setQname(QName name) { + public void setQname(final QName name) { Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies."); this.name = name; } @@ -68,7 +68,7 @@ public final class EmptyNodeWrapper implements NodeWrapper>, Node } @Override - public void setNamespace(URI namespace) { + public void setNamespace(final URI namespace) { Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies."); this.namespace = namespace; } @@ -103,6 +103,7 @@ public final class EmptyNodeWrapper implements NodeWrapper>, Node } @Override + @Deprecated public CompositeNode getParent() { return unwrap().getParent(); } @@ -118,7 +119,7 @@ public final class EmptyNodeWrapper implements NodeWrapper>, Node } @Override - public Void setValue(Void value) { + public Void setValue(final Void value) { return null; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java index 265cc5db45..14b8282312 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java @@ -47,7 +47,7 @@ public class RestCodec { private RestCodec() { } - public static final Codec from(TypeDefinition typeDefinition, MountInstance mountPoint) { + public static final Codec from(final TypeDefinition typeDefinition, final MountInstance mountPoint) { return new ObjectCodec(typeDefinition, mountPoint); } @@ -62,7 +62,7 @@ public class RestCodec { private final TypeDefinition type; - private ObjectCodec(TypeDefinition typeDefinition, MountInstance mountPoint) { + private ObjectCodec(final TypeDefinition typeDefinition, final MountInstance mountPoint) { type = RestUtil.resolveBaseTypeFrom(typeDefinition); if (type instanceof IdentityrefTypeDefinition) { identityrefCodec = new IdentityrefCodecImpl(mountPoint); @@ -78,7 +78,7 @@ public class RestCodec { @SuppressWarnings("unchecked") @Override - public Object deserialize(Object input) { + public Object deserialize(final Object input) { try { if (type instanceof IdentityrefTypeDefinition) { if (input instanceof IdentityValuesDTO) { @@ -116,7 +116,7 @@ public class RestCodec { } } } catch (ClassCastException e) { // TODO remove this catch when - // everyone use codecs + // everyone use codecs logger.error( "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e); @@ -126,7 +126,7 @@ public class RestCodec { @SuppressWarnings("unchecked") @Override - public Object serialize(Object input) { + public Object serialize(final Object input) { try { if (type instanceof IdentityrefTypeDefinition) { return identityrefCodec.serialize(input); @@ -146,7 +146,7 @@ public class RestCodec { } } } catch (ClassCastException e) { // TODO remove this catch when - // everyone use codecs + // everyone use codecs logger.error( "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e); @@ -162,17 +162,17 @@ public class RestCodec { private final MountInstance mountPoint; - public IdentityrefCodecImpl(MountInstance mountPoint) { + public IdentityrefCodecImpl(final MountInstance mountPoint) { this.mountPoint = mountPoint; } @Override - public IdentityValuesDTO serialize(QName data) { + public IdentityValuesDTO serialize(final QName data) { return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null); } @Override - public QName deserialize(IdentityValuesDTO data) { + public QName deserialize(final IdentityValuesDTO data) { IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0); Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint); if (module == null) { @@ -189,12 +189,12 @@ public class RestCodec { public static class LeafrefCodecImpl implements LeafrefCodec { @Override - public String serialize(Object data) { + public String serialize(final Object data) { return String.valueOf(data); } @Override - public Object deserialize(String data) { + public Object deserialize(final String data) { return data; } @@ -204,15 +204,14 @@ public class RestCodec { private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class); private final MountInstance mountPoint; - public InstanceIdentifierCodecImpl(MountInstance mountPoint) { + public InstanceIdentifierCodecImpl(final MountInstance mountPoint) { this.mountPoint = mountPoint; } @Override - public IdentityValuesDTO serialize(InstanceIdentifier data) { - List pathArguments = data.getPath(); + public IdentityValuesDTO serialize(final InstanceIdentifier data) { IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO(); - for (PathArgument pathArgument : pathArguments) { + for (PathArgument pathArgument : data.getPathArguments()) { IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType()); if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) { List predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument) @@ -230,7 +229,7 @@ public class RestCodec { } @Override - public InstanceIdentifier deserialize(IdentityValuesDTO data) { + public InstanceIdentifier deserialize(final IdentityValuesDTO data) { List result = new ArrayList(); IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0); Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint); @@ -293,10 +292,10 @@ public class RestCodec { } } - return result.isEmpty() ? null : new InstanceIdentifier(result); + return result.isEmpty() ? null : InstanceIdentifier.create(result); } - private List keyValuesToPredicateList(Map keyValues) { + private List keyValuesToPredicateList(final Map keyValues) { List result = new ArrayList<>(); for (QName qName : keyValues.keySet()) { Object value = keyValues.get(qName); @@ -305,7 +304,7 @@ public class RestCodec { return result; } - private IdentityValue qNameToIdentityValue(QName qName) { + private IdentityValue qNameToIdentityValue(final QName qName) { if (qName != null) { return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName(), qName.getPrefix()); } @@ -313,7 +312,7 @@ public class RestCodec { } } - private static Module getModuleByNamespace(String namespace, MountInstance mountPoint) { + private static Module getModuleByNamespace(final String namespace, final MountInstance mountPoint) { URI validNamespace = resolveValidNamespace(namespace, mountPoint); Module module = null; @@ -329,7 +328,7 @@ public class RestCodec { return module; } - private static URI resolveValidNamespace(String namespace, MountInstance mountPoint) { + private static URI resolveValidNamespace(final String namespace, final MountInstance mountPoint) { URI validNamespace; if (mountPoint != null) { validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java index 4716a02be2..5a16c04aed 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java @@ -15,6 +15,7 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; + import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -27,10 +28,12 @@ import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.concurrent.Future; + import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; + import org.apache.commons.lang3.StringUtils; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.sal.core.api.mount.MountInstance; @@ -112,7 +115,7 @@ public class RestconfImpl implements RestconfService { final List> modulesAsData = new ArrayList>(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); Set allModules = this.controllerContext.getAllModules(); for (final Module module : allModules) { @@ -121,7 +124,7 @@ public class RestconfImpl implements RestconfService { } final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); return new StructuredData(modulesNode, modulesSchemaNode, null); @@ -134,13 +137,13 @@ public class RestconfImpl implements RestconfService { final List> streamsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); for (final String streamName : availableStreams) { streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode)); } final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); QName qName = streamsSchemaNode.getQName(); final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData); return new StructuredData(streamsNode, streamsSchemaNode, null); @@ -152,27 +155,27 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); } else { throw new RestconfDocumentedException( "URI has bad format. If modules behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } final List> modulesAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); for (final Module module : modules) { modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode)); } final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); return new StructuredData(modulesNode, modulesSchemaNode, mountPoint); @@ -185,7 +188,7 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision); } @@ -196,13 +199,13 @@ public class RestconfImpl implements RestconfService { if (module == null) { throw new RestconfDocumentedException( "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" + - moduleNameAndRevision.getRevision() + "' was not found.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + moduleNameAndRevision.getRevision() + "' was not found.", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); } Module restconfModule = this.getRestconfModule(); final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode); return new StructuredData(moduleNode, moduleSchemaNode, mountPoint); } @@ -219,36 +222,36 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); } else { throw new RestconfDocumentedException( "URI has bad format. If operations behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } return this.operationsFromModulesToStructuredData(modules, mountPoint); } private StructuredData operationsFromModulesToStructuredData(final Set modules, - final MountInstance mountPoint) { + final MountInstance mountPoint) { final List> operationsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); + restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); QName qName = operationsSchemaNode.getQName(); SchemaPath path = operationsSchemaNode.getPath(); ContainerSchemaNodeBuilder containerSchemaNodeBuilder = - new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path); + new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path); final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder; for (final Module module : modules) { Set rpcs = module.getRpcs(); for (final RpcDefinition rpc : rpcs) { QName rpcQName = rpc.getQName(); SimpleNode immutableSimpleNode = - NodeFactory.createImmutableSimpleNode(rpcQName, null, null); + NodeFactory.createImmutableSimpleNode(rpcQName, null, null); operationsAsData.add(immutableSimpleNode); String name = module.getName(); @@ -264,7 +267,7 @@ public class RestconfImpl implements RestconfService { } final CompositeNode operationsNode = - NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); + NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build(); return new StructuredData(operationsNode, schemaNode, mountPoint); } @@ -316,34 +319,34 @@ public class RestconfImpl implements RestconfService { final List> streamNodeValues = new ArrayList>(); List instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode), - "name"); + "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), null, - streamName)); + streamName)); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "description"); + ((DataNodeContainer) streamSchemaNode), "description"); final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(descriptionSchemaNode.getQName(), null, - "DESCRIPTION_PLACEHOLDER")); + "DESCRIPTION_PLACEHOLDER")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "replay-support"); + ((DataNodeContainer) streamSchemaNode), "replay-support"); final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null, - Boolean.valueOf(true))); + Boolean.valueOf(true))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time"); + ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time"); final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(), - null, "")); + null, "")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) streamSchemaNode), "events"); + ((DataNodeContainer) streamSchemaNode), "events"); final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); streamNodeValues.add(NodeFactory.createImmutableSimpleNode(eventsSchemaNode.getQName(), - null, "")); + null, "")); return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues); } @@ -351,30 +354,30 @@ public class RestconfImpl implements RestconfService { private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) { final List> moduleNodeValues = new ArrayList>(); List instanceDataChildrenByName = - this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name"); + this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), - null, module.getName())); + null, module.getName())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "revision"); + ((DataNodeContainer) moduleSchemaNode), "revision"); final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); Date _revision = module.getRevision(); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(revisionSchemaNode.getQName(), null, - REVISION_FORMAT.format(_revision))); + REVISION_FORMAT.format(_revision))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "namespace"); + ((DataNodeContainer) moduleSchemaNode), "namespace"); final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(namespaceSchemaNode.getQName(), null, - module.getNamespace().toString())); + module.getNamespace().toString())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) moduleSchemaNode), "feature"); + ((DataNodeContainer) moduleSchemaNode), "feature"); final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); for (final FeatureDefinition feature : module.getFeatures()) { moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(featureSchemaNode.getQName(), null, - feature.getQName().getLocalName())); + feature.getQName().getLocalName())); } return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues); @@ -391,7 +394,7 @@ public class RestconfImpl implements RestconfService { QName rpcName = rpc.getRpcDefinition().getQName(); URI rpcNamespace = rpcName.getNamespace(); if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) && - Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { + Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition()); } @@ -400,33 +403,33 @@ public class RestconfImpl implements RestconfService { return callRpc(rpc, payload); } - private void validateInput(DataSchemaNode inputSchema, CompositeNode payload) { + private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) { if( inputSchema != null && payload == null ) { //expected a non null payload throw new RestconfDocumentedException( "Input is required.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + ErrorType.PROTOCOL, + ErrorTag.MALFORMED_MESSAGE ); } else if( inputSchema == null && payload != null ) { //did not expect any input throw new RestconfDocumentedException( "No input expected.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + ErrorType.PROTOCOL, + ErrorTag.MALFORMED_MESSAGE ); } //else //{ - //TODO: Validate "mandatory" and "config" values here??? Or should those be + //TODO: Validate "mandatory" and "config" values here??? Or should those be // validate in a more central location inside MD-SAL core. //} } private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, - final RpcDefinition rpc) { + final RpcDefinition rpc) { final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null); final SimpleNode pathNode = value == null ? null : - value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") ); + value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") ); final Object pathValue = pathNode == null ? null : pathNode.getValue(); if (!(pathValue instanceof InstanceIdentifier)) { @@ -437,7 +440,7 @@ public class RestconfImpl implements RestconfService { final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue); String streamName = null; - if (!Iterables.isEmpty(pathIdentifier.getPath())) { + if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) { String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier); streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier); } @@ -449,12 +452,12 @@ public class RestconfImpl implements RestconfService { } final SimpleNode streamNameNode = NodeFactory.createImmutableSimpleNode( - QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName); + QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName); final List> output = new ArrayList>(); output.add(streamNameNode); final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode( - rpc.getOutput().getQName(), null, output, null, null); + rpc.getOutput().getQName(), null, output, null, null); if (!Notificator.existListenerFor(pathIdentifier)) { Notificator.createListener(pathIdentifier, streamName); @@ -547,14 +550,14 @@ public class RestconfImpl implements RestconfService { return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null); } - private void checkRpcSuccessAndThrowException(RpcResult rpcResult) { + private void checkRpcSuccessAndThrowException(final RpcResult rpcResult) { if (rpcResult.isSuccessful() == false) { Collection rpcErrors = rpcResult.getErrors(); if( rpcErrors == null || rpcErrors.isEmpty() ) { throw new RestconfDocumentedException( - "The operation was not successful and there were no RPC errors returned", - ErrorType.RPC, ErrorTag.OPERATION_FAILED ); + "The operation was not successful and there were no RPC errors returned", + ErrorType.RPC, ErrorTag.OPERATION_FAILED ); } List errorList = Lists.newArrayList(); @@ -567,7 +570,7 @@ public class RestconfImpl implements RestconfService { } @Override - public StructuredData readConfigurationData(final String identifier, UriInfo info) { + public StructuredData readConfigurationData(final String identifier, final UriInfo info) { final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); CompositeNode data = null; MountInstance mountPoint = iiWithData.getMountPoint(); @@ -583,7 +586,7 @@ public class RestconfImpl implements RestconfService { } @SuppressWarnings("unchecked") - private > T pruneDataAtDepth( T node, Integer depth ) { + private > T pruneDataAtDepth( final T node, final Integer depth ) { if( depth == null ) { return node; } @@ -603,7 +606,7 @@ public class RestconfImpl implements RestconfService { } } - private Integer parseDepthParameter( UriInfo info ) { + private Integer parseDepthParameter( final UriInfo info ) { String param = info.getQueryParameters( false ).getFirst( "depth" ); if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) { return null; @@ -628,7 +631,7 @@ public class RestconfImpl implements RestconfService { } @Override - public StructuredData readOperationalData(final String identifier, UriInfo info) { + public StructuredData readOperationalData(final String identifier, final UriInfo info) { final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier); CompositeNode data = null; MountInstance mountPoint = iiWithData.getMountPoint(); @@ -656,7 +659,7 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { status = broker.commitConfigurationDataPutBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value).get(); + mountPoint, iiWithData.getInstanceIdentifier(), value).get(); } else { status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get(); } @@ -665,8 +668,9 @@ public class RestconfImpl implements RestconfService { throw new RestconfDocumentedException( "Error updating data", e ); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.OK).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -682,14 +686,14 @@ public class RestconfImpl implements RestconfService { URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( - "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); } InstanceIdWithSchemaNode iiWithData = null; CompositeNode value = null; if (this.representsMountPointRootData(payload)) { - // payload represents mount point data and URI represents path to the mount point + // payload represents mount point data and URI represents path to the mount point if (this.endsWithMountPoint(identifier)) { throw new RestconfDocumentedException( @@ -705,7 +709,7 @@ public class RestconfImpl implements RestconfService { } else { final InstanceIdWithSchemaNode incompleteInstIdWithData = - this.controllerContext.toInstanceIdentifier(identifier); + this.controllerContext.toInstanceIdentifier(identifier); final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode(); MountInstance mountPoint = incompleteInstIdWithData.getMountPoint(); final Module module = this.findModule(mountPoint, payload); @@ -717,7 +721,7 @@ public class RestconfImpl implements RestconfService { String payloadName = this.getName(payload); final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace( - parentSchema, payloadName, module.getNamespace()); + parentSchema, payloadName, module.getNamespace()); value = this.normalizeNode(payload, schemaNode, mountPoint); iiWithData = this.addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode); @@ -728,13 +732,13 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } else { Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } } @@ -746,8 +750,9 @@ public class RestconfImpl implements RestconfService { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.NO_CONTENT).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -763,8 +768,8 @@ public class RestconfImpl implements RestconfService { URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( - "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); } final Module module = this.findModule(null, payload); @@ -776,7 +781,7 @@ public class RestconfImpl implements RestconfService { String payloadName = this.getName(payload); final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace( - module, payloadName, module.getNamespace()); + module, payloadName, module.getNamespace()); final CompositeNode value = this.normalizeNode(payload, schemaNode, null); final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode); RpcResult status = null; @@ -785,13 +790,13 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } else { Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } } @@ -803,8 +808,9 @@ public class RestconfImpl implements RestconfService { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.NO_CONTENT).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -818,7 +824,7 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { status = broker.commitConfigurationDataDeleteBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier()).get(); + mountPoint, iiWithData.getInstanceIdentifier()).get(); } else { status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get(); @@ -828,8 +834,9 @@ public class RestconfImpl implements RestconfService { throw new RestconfDocumentedException( "Error creating data", e ); } - if( status.getResult() == TransactionStatus.COMMITED ) + if( status.getResult() == TransactionStatus.COMMITED ) { return Response.status(Status.OK).build(); + } return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } @@ -898,8 +905,8 @@ public class RestconfImpl implements RestconfService { } private InstanceIdWithSchemaNode addLastIdentifierFromData( - final InstanceIdWithSchemaNode identifierWithSchemaNode, - final CompositeNode data, final DataSchemaNode schemaOfData) { + final InstanceIdWithSchemaNode identifierWithSchemaNode, + final CompositeNode data, final DataSchemaNode schemaOfData) { InstanceIdentifier instanceIdentifier = null; if (identifierWithSchemaNode != null) { instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier(); @@ -932,7 +939,7 @@ public class RestconfImpl implements RestconfService { } private HashMap resolveKeysFromData(final ListSchemaNode listNode, - final CompositeNode dataNode) { + final CompositeNode dataNode) { final HashMap keyValues = new HashMap(); List _keyDefinition = listNode.getKeyDefinition(); for (final QName key : _keyDefinition) { @@ -963,7 +970,7 @@ public class RestconfImpl implements RestconfService { private boolean endsWithMountPoint(final String identifier) { return identifier.endsWith(ControllerContext.MOUNT) || - identifier.endsWith(ControllerContext.MOUNT + "/"); + identifier.endsWith(ControllerContext.MOUNT + "/"); } private boolean representsMountPointRootData(final CompositeNode data) { @@ -983,7 +990,7 @@ public class RestconfImpl implements RestconfService { } private CompositeNode normalizeNode(final CompositeNode node, final DataSchemaNode schema, - final MountInstance mountPoint) { + final MountInstance mountPoint) { if (schema == null) { QName nodeType = node == null ? null : node.getNodeType(); String localName = nodeType == null ? null : nodeType.getLocalName(); @@ -1007,7 +1014,7 @@ public class RestconfImpl implements RestconfService { } catch (IllegalArgumentException e) { throw new RestconfDocumentedException( - e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } @@ -1018,8 +1025,8 @@ public class RestconfImpl implements RestconfService { } private void normalizeNode(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + final DataSchemaNode schema, final QName previousAugment, + final MountInstance mountPoint) { if (schema == null) { throw new RestconfDocumentedException( "Data has bad format.\n\"" + nodeBuilder.getLocalName() + @@ -1036,19 +1043,19 @@ public class RestconfImpl implements RestconfService { if (nodeBuilder.getQname() == null) { throw new RestconfDocumentedException( "Data has bad format.\nIf data is in XML format then namespace for \"" + - nodeBuilder.getLocalName() + - "\" should be \"" + schema.getQName().getNamespace() + "\".\n" + - "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() + - "\" should be corresponding to namespace \"" + - schema.getQName().getNamespace() + "\".", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + nodeBuilder.getLocalName() + + "\" should be \"" + schema.getQName().getNamespace() + "\".\n" + + "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() + + "\" should be corresponding to namespace \"" + + schema.getQName().getNamespace() + "\".", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } if ( nodeBuilder instanceof CompositeNodeWrapper ) { if( schema instanceof DataNodeContainer ) { normalizeCompositeNode( (CompositeNodeWrapper)nodeBuilder, (DataNodeContainer)schema, - mountPoint, currentAugment ); + mountPoint, currentAugment ); } else if( schema instanceof AnyXmlSchemaNode ) { normalizeAnyXmlNode( (CompositeNodeWrapper)nodeBuilder, (AnyXmlSchemaNode)schema ); @@ -1062,7 +1069,7 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeAnyXmlNode( CompositeNodeWrapper compositeNode, AnyXmlSchemaNode schema ) { + private void normalizeAnyXmlNode( final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema ) { List> children = compositeNode.getValues(); for( NodeWrapper child : children ) { child.setNamespace( schema.getQName().getNamespace() ); @@ -1072,7 +1079,7 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeEmptyNode( EmptyNodeWrapper emptyNodeBuilder, DataSchemaNode schema ) { + private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) { if ((schema instanceof LeafSchemaNode)) { emptyNodeBuilder.setComposite(false); } @@ -1084,8 +1091,8 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeSimpleNode( SimpleNodeWrapper simpleNode, DataSchemaNode schema, - MountInstance mountPoint ) { + private void normalizeSimpleNode( final SimpleNodeWrapper simpleNode, final DataSchemaNode schema, + final MountInstance mountPoint ) { final Object value = simpleNode.getValue(); Object inputValue = value; TypeDefinition typeDefinition = this.typeDefinition(schema); @@ -1106,28 +1113,28 @@ public class RestconfImpl implements RestconfService { simpleNode.setValue(outputValue); } - private void normalizeCompositeNode( CompositeNodeWrapper compositeNodeBuilder, - DataNodeContainer schema, MountInstance mountPoint, - QName currentAugment ) { + private void normalizeCompositeNode( final CompositeNodeWrapper compositeNodeBuilder, + final DataNodeContainer schema, final MountInstance mountPoint, + final QName currentAugment ) { final List> children = compositeNodeBuilder.getValues(); for (final NodeWrapper child : children) { final List potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName( - schema, child.getLocalName()); + schema, child.getLocalName()); if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) { StringBuilder builder = new StringBuilder(); for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()) - .append("\n"); + .append("\n"); } throw new RestconfDocumentedException( - "Node \"" + child.getLocalName() + - "\" is added as augment from more than one module. " + - "Therefore node must have namespace (XML format) or module name (JSON format)." + - "\nThe node is added as augment from modules with namespaces:\n" + builder, - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "Node \"" + child.getLocalName() + + "\" is added as augment from more than one module. " + + "Therefore node must have namespace (XML format) or module name (JSON format)." + + "\nThe node is added as augment from modules with namespaces:\n" + builder, + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } boolean rightNodeSchemaFound = false; @@ -1144,8 +1151,8 @@ public class RestconfImpl implements RestconfService { if (!rightNodeSchemaFound) { throw new RestconfDocumentedException( - "Schema node \"" + child.getLocalName() + "\" was not found in module.", - ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); + "Schema node \"" + child.getLocalName() + "\" was not found in module.", + ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); } } @@ -1162,24 +1169,24 @@ public class RestconfImpl implements RestconfService { if (!foundKey) { throw new RestconfDocumentedException( - "Missing key in URI \"" + listKey.getLocalName() + - "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "Missing key in URI \"" + listKey.getLocalName() + + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } } } } private QName normalizeNodeName(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + final DataSchemaNode schema, final QName previousAugment, + final MountInstance mountPoint) { QName validQName = schema.getQName(); QName currentAugment = previousAugment; if (schema.isAugmenting()) { currentAugment = schema.getQName(); } else if (previousAugment != null && - !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) { + !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) { validQName = QName.create(currentAugment, schema.getQName().getLocalName()); } @@ -1192,8 +1199,8 @@ public class RestconfImpl implements RestconfService { } if (nodeBuilder.getNamespace() == null || - Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) || - Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*|| + Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) || + Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*|| Note: this check is wrong - can never be true as it compares a URI with a String not sure what the intention is so commented out... Objects.equal(nodeBuilder.getNamespace(), MOUNT_POINT_MODULE_NAME)*/ ) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java index 3131668ed9..b0959c8398 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java @@ -7,6 +7,8 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Preconditions; + import java.net.URI; import org.opendaylight.yangtools.yang.common.QName; @@ -16,8 +18,6 @@ import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode; import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; -import com.google.common.base.Preconditions; - public final class SimpleNodeWrapper implements NodeWrapper>, SimpleNode { private SimpleNode simpleNode; @@ -27,18 +27,18 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp private URI namespace; private QName name; - public SimpleNodeWrapper(String localName, Object value) { + public SimpleNodeWrapper(final String localName, final Object value) { this.localName = Preconditions.checkNotNull(localName); this.value = value; } - public SimpleNodeWrapper(URI namespace, String localName, Object value) { + public SimpleNodeWrapper(final URI namespace, final String localName, final Object value) { this(localName, value); this.namespace = namespace; } @Override - public void setQname(QName name) { + public void setQname(final QName name) { Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies."); this.name = name; } @@ -65,7 +65,7 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp } @Override - public void setNamespace(URI namespace) { + public void setNamespace(final URI namespace) { Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies."); this.namespace = namespace; } @@ -89,7 +89,7 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp localName = null; name = null; } - return (SimpleNode) simpleNode; + return simpleNode; } @Override @@ -98,6 +98,7 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp } @Override + @Deprecated public CompositeNode getParent() { return unwrap().getParent(); } @@ -108,6 +109,7 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp } @Override + @Deprecated public ModifyAction getModificationAction() { return unwrap().getModificationAction(); } @@ -123,7 +125,7 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp } @Override - public Object setValue(Object value) { + public Object setValue(final Object value) { return unwrap().setValue(value); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java index 6282f37602..925a09337c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java @@ -7,6 +7,12 @@ */ package org.opendaylight.controller.sal.streams.listeners; +import com.google.common.base.Charsets; +import com.google.common.base.Preconditions; +import com.google.common.eventbus.AsyncEventBus; +import com.google.common.eventbus.EventBus; +import com.google.common.eventbus.Subscribe; + import io.netty.channel.Channel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.internal.ConcurrentSet; @@ -23,6 +29,7 @@ import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.Executors; +import java.util.regex.Pattern; import javax.activation.UnsupportedDataTypeException; import javax.xml.parsers.DocumentBuilder; @@ -53,19 +60,17 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import com.google.common.base.Preconditions; -import com.google.common.eventbus.AsyncEventBus; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - /** * {@link ListenerAdapter} is responsible to track events, which occurred by * changing data in data source. */ public class ListenerAdapter implements DataChangeListener { - private static final Logger logger = LoggerFactory - .getLogger(ListenerAdapter.class); + private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class); + private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance(); + private static final TransformerFactory FACTORY = TransformerFactory.newInstance(); + private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$"); + private final XmlMapper xmlMapper = new XmlMapper(); private final SimpleDateFormat rfc3339 = new SimpleDateFormat( "yyyy-MM-dd'T'hh:mm:ssZ"); @@ -77,6 +82,7 @@ public class ListenerAdapter implements DataChangeListener { private final EventBus eventBus; private final EventBusChangeRecorder eventBusChangeRecorder; + /** * Creates new {@link ListenerAdapter} listener specified by path and stream * name. @@ -86,10 +92,10 @@ public class ListenerAdapter implements DataChangeListener { * @param streamName * The name of the stream. */ - ListenerAdapter(InstanceIdentifier path, String streamName) { + ListenerAdapter(final InstanceIdentifier path, final String streamName) { Preconditions.checkNotNull(path); Preconditions - .checkArgument(streamName != null && !streamName.isEmpty()); + .checkArgument(streamName != null && !streamName.isEmpty()); this.path = path; this.streamName = streamName; eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor()); @@ -99,7 +105,7 @@ public class ListenerAdapter implements DataChangeListener { @Override public void onDataChanged( - DataChangeEvent change) { + final DataChangeEvent change) { if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty() || !change.getUpdatedConfigurationData().isEmpty() @@ -118,7 +124,7 @@ public class ListenerAdapter implements DataChangeListener { */ private final class EventBusChangeRecorder { @Subscribe - public void recordCustomerChange(Event event) { + public void recordCustomerChange(final Event event) { if (event.getType() == EventType.REGISTER) { Channel subscriber = event.getSubscriber(); if (!subscribers.contains(subscriber)) { @@ -127,16 +133,16 @@ public class ListenerAdapter implements DataChangeListener { } else if (event.getType() == EventType.DEREGISTER) { subscribers.remove(event.getSubscriber()); Notificator - .removeListenerIfNoSubscriberExists(ListenerAdapter.this); + .removeListenerIfNoSubscriberExists(ListenerAdapter.this); } else if (event.getType() == EventType.NOTIFY) { for (Channel subscriber : subscribers) { if (subscriber.isActive()) { - logger.debug("Data are sent to subscriber {}:", + LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress()); subscriber.writeAndFlush(new TextWebSocketFrame(event .getData())); } else { - logger.debug( + LOG.debug( "Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress()); subscribers.remove(subscriber); @@ -161,7 +167,7 @@ public class ListenerAdapter implements DataChangeListener { * @param type * EventType */ - public Event(EventType type) { + public Event(final EventType type) { this.type = type; } @@ -180,7 +186,7 @@ public class ListenerAdapter implements DataChangeListener { * @param subscriber * Channel */ - public void setSubscriber(Channel subscriber) { + public void setSubscriber(final Channel subscriber) { this.subscriber = subscriber; } @@ -199,7 +205,7 @@ public class ListenerAdapter implements DataChangeListener { * @param String * data. */ - public void setData(String data) { + public void setData(final String data) { this.data = data; } @@ -228,7 +234,7 @@ public class ListenerAdapter implements DataChangeListener { * @return Data in printable form. */ private String prepareXmlFrom( - DataChangeEvent change) { + final DataChangeEvent change) { Document doc = createDocument(); Element notificationElement = doc.createElementNS( "urn:ietf:params:xml:ns:netconf:notification:1.0", @@ -248,22 +254,19 @@ public class ListenerAdapter implements DataChangeListener { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer = tf.newTransformer(); - transformer - .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + Transformer transformer = FACTORY.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty( - "{http://xml.apache.org/xslt}indent-amount", "4"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(doc), new StreamResult( - new OutputStreamWriter(out, "UTF-8"))); + new OutputStreamWriter(out, Charsets.UTF_8))); byte[] charData = out.toByteArray(); return new String(charData, "UTF-8"); } catch (TransformerException | UnsupportedEncodingException e) { String msg = "Error during transformation of Document into String"; - logger.error(msg, e); + LOG.error(msg, e); return msg; } } @@ -275,8 +278,8 @@ public class ListenerAdapter implements DataChangeListener { * Date * @return Data specified by RFC3339. */ - private String toRFC3339(Date d) { - return rfc3339.format(d).replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2"); + private String toRFC3339(final Date d) { + return RFC3339_PATTERN.matcher(rfc3339.format(d)).replaceAll("$1:$2"); } /** @@ -285,15 +288,13 @@ public class ListenerAdapter implements DataChangeListener { * @return {@link Document} document. */ private Document createDocument() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - Document doc = null; + final DocumentBuilder bob; try { - DocumentBuilder bob = dbf.newDocumentBuilder(); - doc = bob.newDocument(); + bob = DBF.newDocumentBuilder(); } catch (ParserConfigurationException e) { return null; } - return doc; + return bob.newDocument(); } /** @@ -306,9 +307,9 @@ public class ListenerAdapter implements DataChangeListener { * @param change * {@link DataChangeEvent} */ - private void addValuesToDataChangedNotificationEventElement(Document doc, - Element dataChangedNotificationEventElement, - DataChangeEvent change) { + private void addValuesToDataChangedNotificationEventElement(final Document doc, + final Element dataChangedNotificationEventElement, + final DataChangeEvent change) { addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement, Store.CONFIG, Operation.CREATED); @@ -348,9 +349,9 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(Document doc, - Set data, Element element, Store store, - Operation operation) { + private void addValuesFromDataToElement(final Document doc, + final Set data, final Element element, final Store store, + final Operation operation) { if (data == null || data.isEmpty()) { return; } @@ -375,9 +376,9 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(Document doc, - Map data, Element element, - Store store, Operation operation) { + private void addValuesFromDataToElement(final Document doc, + final Map data, final Element element, + final Store store, final Operation operation) { if (data == null || data.isEmpty()) { return; } @@ -403,9 +404,9 @@ public class ListenerAdapter implements DataChangeListener { * {@link Operation} * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(Document doc, - InstanceIdentifier path, CompositeNode data, Store store, - Operation operation) { + private Node createDataChangeEventElement(final Document doc, + final InstanceIdentifier path, final CompositeNode data, final Store store, + final Operation operation) { Element dataChangeEventElement = doc.createElement("data-change-event"); Element pathElement = doc.createElement("path"); @@ -440,11 +441,11 @@ public class ListenerAdapter implements DataChangeListener { * {@link CompositeNode} * @return Data in XML format. */ - private Node translateToXml(InstanceIdentifier path, CompositeNode data) { + private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) { DataNodeContainer schemaNode = ControllerContext.getInstance() .getDataNodeContainerFor(path); if (schemaNode == null) { - logger.info( + LOG.info( "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.", path); return null; @@ -453,7 +454,7 @@ public class ListenerAdapter implements DataChangeListener { Document xml = xmlMapper.write(data, schemaNode); return xml.getFirstChild(); } catch (UnsupportedDataTypeException e) { - logger.error( + LOG.error( "Error occured during translation of notification to XML.", e); return null; @@ -468,13 +469,15 @@ public class ListenerAdapter implements DataChangeListener { * @param element * {@link Element} */ - private void addPathAsValueToElement(InstanceIdentifier path, - Element element) { + private void addPathAsValueToElement(final InstanceIdentifier path, + final Element element) { // Map< key = namespace, value = prefix> Map prefixes = new HashMap<>(); InstanceIdentifier instanceIdentifier = path; StringBuilder textContent = new StringBuilder(); - for (PathArgument pathArgument : instanceIdentifier.getPath()) { + + // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275) + for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) { textContent.append("/"); writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes); @@ -514,8 +517,8 @@ public class ListenerAdapter implements DataChangeListener { * @param prefixes * Map of namespaces and prefixes. */ - private static void writeIdentifierWithNamespacePrefix(Element element, - StringBuilder textContent, QName qName, Map prefixes) { + private static void writeIdentifierWithNamespacePrefix(final Element element, + final StringBuilder textContent, final QName qName, final Map prefixes) { String namespace = qName.getNamespace().toString(); String prefix = prefixes.get(namespace); if (prefix == null) { @@ -541,7 +544,7 @@ public class ListenerAdapter implements DataChangeListener { * Collection of prefixes. * @return New prefix which consists of four random characters . */ - private static String generateNewPrefix(Collection prefixes) { + private static String generateNewPrefix(final Collection prefixes) { StringBuilder result = null; Random random = new Random(); do { @@ -571,7 +574,7 @@ public class ListenerAdapter implements DataChangeListener { * ListenerRegistration */ public void setRegistration( - ListenerRegistration registration) { + final ListenerRegistration registration) { this.registration = registration; } @@ -611,9 +614,9 @@ public class ListenerAdapter implements DataChangeListener { * @param subscriber * Channel */ - public void addSubscriber(Channel subscriber) { + public void addSubscriber(final Channel subscriber) { if (!subscriber.isActive()) { - logger.debug("Channel is not active between websocket server and subscriber {}" + LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress()); } Event event = new Event(EventType.REGISTER); @@ -627,8 +630,8 @@ public class ListenerAdapter implements DataChangeListener { * * @param subscriber */ - public void removeSubscriber(Channel subscriber) { - logger.debug("Subscriber {} is removed.", subscriber.remoteAddress()); + public void removeSubscriber(final Channel subscriber) { + LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress()); Event event = new Event(EventType.DEREGISTER); event.setSubscriber(subscriber); eventBus.post(event); @@ -652,7 +655,7 @@ public class ListenerAdapter implements DataChangeListener { private final String value; - private Store(String value) { + private Store(final String value) { this.value = value; } } @@ -666,7 +669,7 @@ public class ListenerAdapter implements DataChangeListener { private final String value; - private Operation(String value) { + private Operation(final String value) { this.value = value; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java index b5d6a6ea9b..26e4936d3f 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java @@ -46,7 +46,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler private WebSocketServerHandshaker handshaker; @Override - protected void channelRead0(ChannelHandlerContext ctx, Object msg) + protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); @@ -64,8 +64,8 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * @param req * FullHttpRequest */ - private void handleHttpRequest(ChannelHandlerContext ctx, - FullHttpRequest req) throws Exception { + private void handleHttpRequest(final ChannelHandlerContext ctx, + final FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, @@ -97,8 +97,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler getWebSocketLocation(req), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { - WebSocketServerHandshakerFactory - .sendUnsupportedWebSocketVersionResponse(ctx.channel()); + WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } @@ -115,8 +114,8 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * @param res * FullHttpResponse */ - private static void sendHttpResponse(ChannelHandlerContext ctx, - HttpRequest req, FullHttpResponse res) { + private static void sendHttpResponse(final ChannelHandlerContext ctx, + final HttpRequest req, final FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), @@ -141,8 +140,8 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * @param frame * {@link WebSocketFrame} */ - private void handleWebSocketFrame(ChannelHandlerContext ctx, - WebSocketFrame frame) throws IOException { + private void handleWebSocketFrame(final ChannelHandlerContext ctx, + final WebSocketFrame frame) throws IOException { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); @@ -164,7 +163,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) + public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (cause instanceof java.nio.channels.ClosedChannelException == false) { // cause.printStackTrace(); @@ -179,7 +178,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * HTTP request from which the location will be returned * @return String representation of web socket location. */ - private static String getWebSocketLocation(HttpRequest req) { + private static String getWebSocketLocation(final HttpRequest req) { return "http://" + req.headers().get(HOST) + req.getUri(); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java index 07d781028b..3f2c212bd8 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java @@ -226,7 +226,7 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112"))); - return new InstanceIdentifier(pathArguments); + return InstanceIdentifier.create(pathArguments); } private InstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException { @@ -235,7 +235,7 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1"))); pathArguments.add(new NodeWithValue(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1")); - return new InstanceIdentifier(pathArguments); + return InstanceIdentifier.create(pathArguments); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java index f0a232fba6..41a1c3827d 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java @@ -7,8 +7,8 @@ */ package org.opendaylight.controller.sal.restconf.impl.test; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; @@ -77,7 +77,7 @@ public class RestGetOperationTest extends JerseyTest { Object key; Object data; // List for a CompositeNode, value Object for a SimpleNode - NodeData( Object key, Object data ) { + NodeData( final Object key, final Object data ) { this.key = key; this.data = data; } @@ -186,7 +186,7 @@ public class RestGetOperationTest extends JerseyTest { */ @Test public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException, - ParseException { + ParseException { InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList(); when( brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class), @@ -214,7 +214,7 @@ public class RestGetOperationTest extends JerseyTest { parameters.add(new InstanceIdentifier.NodeIdentifier(qNameCont)); parameters.add(new InstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList, "GigabitEthernet0/0/0/0")); - return new InstanceIdentifier(parameters); + return InstanceIdentifier.create(parameters); } @Test @@ -356,7 +356,7 @@ public class RestGetOperationTest extends JerseyTest { } - private Matcher validateOperationsResponseJson(String searchIn, String rpcName, String moduleName) { + private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) { StringBuilder regex = new StringBuilder(); regex.append("^"); @@ -390,7 +390,7 @@ public class RestGetOperationTest extends JerseyTest { } - private Matcher validateOperationsResponseXml(String searchIn, String rpcName, String namespace) { + private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) { StringBuilder regex = new StringBuilder(); regex.append("^"); @@ -448,11 +448,11 @@ public class RestGetOperationTest extends JerseyTest { assertTrue( "module1-behind-mount-point in json wasn't found", prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody) - .find()); + .find()); assertTrue( "module2-behind-mount-point in json wasn't found", prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody) - .find()); + .find()); } @@ -488,13 +488,13 @@ public class RestGetOperationTest extends JerseyTest { assertTrue( "module1-behind-mount-point in json wasn't found", prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody) - .find()); + .find()); split = responseBody.split(">() { - @Override - public MultivaluedMap answer( InvocationOnMock invocation ) { - return paramMap; - } - } ); + new Answer>() { + @Override + public MultivaluedMap answer( final InvocationOnMock invocation ) { + return paramMap; + } + } ); getDataWithInvalidDepthParameterTest( mockInfo ); @@ -821,18 +821,18 @@ public class RestGetOperationTest extends JerseyTest { getDataWithInvalidDepthParameterTest( mockInfo ); } - private void getDataWithInvalidDepthParameterTest( UriInfo uriInfo ) { + private void getDataWithInvalidDepthParameterTest( final UriInfo uriInfo ) { try { restconfImpl.readConfigurationData( "nested-module:depth1-cont", uriInfo ); fail( "Expected RestconfDocumentedException" ); } catch( RestconfDocumentedException e ) { assertTrue( "Unexpected error message: " + e.getErrors().get( 0 ).getErrorMessage(), - e.getErrors().get( 0 ).getErrorMessage().contains( "depth" ) ); + e.getErrors().get( 0 ).getErrorMessage().contains( "depth" ) ); } } - private void verifyXMLResponse( Response response, NodeData nodeData ) { + private void verifyXMLResponse( final Response response, final NodeData nodeData ) { Document doc = TestUtils.loadDocumentFrom( (InputStream) response.getEntity() ); assertNotNull( "Could not parse XML document", doc ); @@ -843,14 +843,14 @@ public class RestGetOperationTest extends JerseyTest { } @SuppressWarnings("unchecked") - private void verifyContainerElement( Element element, NodeData nodeData ) { + private void verifyContainerElement( final Element element, final NodeData nodeData ) { assertEquals( "Element local name", nodeData.key, element.getNodeName() ); NodeList childNodes = element.getChildNodes(); if( nodeData.data == null ) { // empty container assertTrue( "Expected no child elements for \"" + element.getNodeName() + "\"", - childNodes.getLength() == 0 ); + childNodes.getLength() == 0 ); return; } @@ -868,41 +868,41 @@ public class RestGetOperationTest extends JerseyTest { Element actualElement = (Element)actualChild; NodeData expChild = expChildMap.remove( actualElement.getNodeName() ); assertNotNull( "Unexpected child element for parent \"" + element.getNodeName() + - "\": " + actualElement.getNodeName(), expChild ); + "\": " + actualElement.getNodeName(), expChild ); if( expChild.data == null || expChild.data instanceof List ) { verifyContainerElement( actualElement, expChild ); } else { assertEquals( "Text content for element: " + actualElement.getNodeName(), - expChild.data, actualElement.getTextContent() ); + expChild.data, actualElement.getTextContent() ); } } if( !expChildMap.isEmpty() ) { fail( "Missing elements for parent \"" + element.getNodeName() + - "\": " + expChildMap.keySet() ); + "\": " + expChildMap.keySet() ); } } - private NodeData expectContainer( String name, NodeData... childData ) { + private NodeData expectContainer( final String name, final NodeData... childData ) { return new NodeData( name, Lists.newArrayList( childData ) ); } - private NodeData expectEmptyContainer( String name ) { + private NodeData expectEmptyContainer( final String name ) { return new NodeData( name, null ); } - private NodeData expectLeaf( String name, Object value ) { + private NodeData expectLeaf( final String name, final Object value ) { return new NodeData( name, value ); } - private QName toNestedQName( String localName ) { + private QName toNestedQName( final String localName ) { return QName.create( "urn:nested:module", "2014-06-3", localName ); } @SuppressWarnings("unchecked") - private CompositeNode toCompositeNode( NodeData nodeData ) { + private CompositeNode toCompositeNode( final NodeData nodeData ) { CompositeNodeBuilder builder = ImmutableCompositeNode.builder(); builder.setQName( (QName) nodeData.key ); @@ -918,11 +918,11 @@ public class RestGetOperationTest extends JerseyTest { return builder.toInstance(); } - private NodeData toCompositeNodeData( QName key, NodeData... childData ) { + private NodeData toCompositeNodeData( final QName key, final NodeData... childData ) { return new NodeData( key, Lists.newArrayList( childData ) ); } - private NodeData toSimpleNodeData( QName key, Object value ) { + private NodeData toSimpleNodeData( final QName key, final Object value ) { return new NodeData( key, value ); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java index 33d4b325be..efdb7b240c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java @@ -14,6 +14,8 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.collect.Iterables; + import java.io.FileNotFoundException; import java.util.Set; @@ -131,7 +133,7 @@ public class URITest { initMountService(true); InstanceIdWithSchemaNode instanceIdentifier = controllerContext .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/"); - assertEquals(true, instanceIdentifier.getInstanceIdentifier().getPath().isEmpty()); + assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments())); } @Test @@ -152,7 +154,7 @@ public class URITest { .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class"); } - public void initMountService(boolean withSchema) { + public void initMountService(final boolean withSchema) { MountService mountService = mock(MountService.class); controllerContext.setMountService(mountService); BrokerFacade brokerFacade = mock(BrokerFacade.class); @@ -163,10 +165,11 @@ public class URITest { Set modules2 = TestUtils.loadModulesFrom("/test-config-data/yang2"); SchemaContext schemaContext2 = TestUtils.loadSchemaContext(modules2); MountInstance mountInstance = mock(MountInstance.class); - if (withSchema) + if (withSchema) { when(mountInstance.getSchemaContext()).thenReturn(schemaContext2); - else + } else { when(mountInstance.getSchemaContext()).thenReturn(null); + } when(mountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance); } } diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java index 0e929afc84..755ca75015 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.lang3.BooleanUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -249,7 +250,7 @@ public class ModelGenerator { if (node instanceof LeafSchemaNode) { property = processLeafNode((LeafSchemaNode) node); } else if (node instanceof ListSchemaNode) { - property = processListSchemaNode((ListSchemaNode) node, moduleName, models); + property = processListSchemaNode((ListSchemaNode) node, moduleName, models, isConfig); } else if (node instanceof LeafListSchemaNode) { property = processLeafListNode((LeafListSchemaNode) node); @@ -354,15 +355,17 @@ public class ModelGenerator { * * @param listNode * @param moduleName + * @param isConfig * @return * @throws JSONException * @throws IOException */ private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName, - JSONObject models) throws JSONException, IOException { + JSONObject models, Boolean isConfig) throws JSONException, IOException { Set listChildren = listNode.getChildNodes(); - String fileName = listNode.getQName().getLocalName(); + String fileName = (BooleanUtils.isNotFalse(isConfig)?OperationBuilder.CONFIG:OperationBuilder.OPERATIONAL) + + listNode.getQName().getLocalName(); JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models); JSONObject childSchema = getSchemaTemplate(); @@ -541,12 +544,15 @@ public class ModelGenerator { private void processUnionType(UnionTypeDefinition unionType, JSONObject property) throws JSONException { - List> unionTypes = unionType.getTypes(); - JSONArray unionArray = new JSONArray(); - for (TypeDefinition typeDef : unionTypes) { - unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass())); + StringBuilder type = new StringBuilder(); + for (TypeDefinition typeDef : unionType.getTypes() ) { + if( type.length() > 0 ){ + type.append( " or " ); + } + type.append(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass())); } - property.put(TYPE_KEY, unionArray); + + property.put(TYPE_KEY, type ); } /** diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java index b996bf1234..fcabb088f4 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java @@ -46,7 +46,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount private final Map instanceIdToLongId = new TreeMap<>( new Comparator() { @Override - public int compare(InstanceIdentifier o1, InstanceIdentifier o2) { + public int compare(final InstanceIdentifier o1, final InstanceIdentifier o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); @@ -71,12 +71,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return urlToId; } - public void setGlobalSchema(SchemaService globalSchema) { + public void setGlobalSchema(final SchemaService globalSchema) { this.globalSchema = globalSchema; } - private String findModuleName(InstanceIdentifier id, SchemaContext context) { - PathArgument rootQName = id.getPath().get(0); + private String findModuleName(final InstanceIdentifier id, final SchemaContext context) { + PathArgument rootQName = id.getPathArguments().iterator().next(); for (Module mod : context.getModules()) { if (mod.getDataChildByName(rootQName.getNodeType()) != null) { return mod.getName(); @@ -85,40 +85,39 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return null; } - private String generateUrlPrefixFromInstanceID(InstanceIdentifier key, String moduleName) { - List path = key.getPath(); + private String generateUrlPrefixFromInstanceID(final InstanceIdentifier key, final String moduleName) { StringBuilder builder = new StringBuilder(); if (moduleName != null) { builder.append(moduleName); - builder.append(":"); + builder.append(':'); } boolean first = true; - for (PathArgument arg : path) { + for (PathArgument arg : key.getPathArguments()) { String name = arg.getNodeType().getLocalName(); if (first) { first = false; } else { - builder.append("/"); + builder.append('/'); } builder.append(name); if (arg instanceof InstanceIdentifier.NodeIdentifierWithPredicates) { NodeIdentifierWithPredicates nodeId = (NodeIdentifierWithPredicates) arg; for (Entry entry : nodeId.getKeyValues().entrySet()) { - builder.append("/").append(entry.getValue()); + builder.append('/').append(entry.getValue()); } } } - return builder.append("/").toString(); + return builder.append('/').toString(); } - private String getYangMountUrl(InstanceIdentifier key) { + private String getYangMountUrl(final InstanceIdentifier key) { String modName = findModuleName(key, globalSchema.getGlobalContext()); return generateUrlPrefixFromInstanceID(key, modName) + "yang-ext:mount/"; } - public ResourceList getResourceList(UriInfo uriInfo, Long id) { + public ResourceList getResourceList(final UriInfo uriInfo, final Long id) { InstanceIdentifier iid = getInstanceId(id); if (iid == null) { return null; // indicating not found. @@ -139,7 +138,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return list; } - private InstanceIdentifier getInstanceId(Long id) { + private InstanceIdentifier getInstanceId(final Long id) { InstanceIdentifier instanceId; synchronized (lock) { instanceId = longIdToInstanceId.get(id); @@ -147,7 +146,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return instanceId; } - private SchemaContext getSchemaContext(InstanceIdentifier id) { + private SchemaContext getSchemaContext(final InstanceIdentifier id) { if (id == null) { return null; @@ -165,7 +164,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return context; } - public ApiDeclaration getMountPointApi(UriInfo uriInfo, Long id, String module, String revision) { + public ApiDeclaration getMountPointApi(final UriInfo uriInfo, final Long id, final String module, final String revision) { InstanceIdentifier iid = getInstanceId(id); SchemaContext context = getSchemaContext(iid); String urlPrefix = getYangMountUrl(iid); @@ -179,7 +178,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return super.getApiDeclaration(module, revision, uriInfo, context, urlPrefix); } - private ApiDeclaration generateDataStoreApiDoc(UriInfo uriInfo, String context) { + private ApiDeclaration generateDataStoreApiDoc(final UriInfo uriInfo, final String context) { ApiDeclaration declaration = super.createApiDeclaration(createBasePathFromUriInfo(uriInfo)); List apis = new LinkedList<>(); @@ -194,7 +193,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount } - private Api createGetApi(String datastore, String note, String context) { + private Api createGetApi(final String datastore, final String note, final String context) { Operation getConfig = new Operation(); getConfig.setMethod("GET"); getConfig.setNickname("GET " + datastore); @@ -207,12 +206,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount return api; } - public void setMountService(MountProvisionService mountService) { + public void setMountService(final MountProvisionService mountService) { this.mountService = mountService; } @Override - public void onMountPointCreated(InstanceIdentifier path) { + public void onMountPointCreated(final InstanceIdentifier path) { synchronized (lock) { Long idLong = idKey.incrementAndGet(); instanceIdToLongId.put(path, idLong); @@ -221,7 +220,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount } @Override - public void onMountPointRemoved(InstanceIdentifier path) { + public void onMountPointRemoved(final InstanceIdentifier path) { synchronized (lock) { Long id = instanceIdToLongId.remove(path); longIdToInstanceId.remove(id); diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html b/opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html index 2816f79e24..05a76a4cb7 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html @@ -24,7 +24,6 @@ -