Merge "Complete implementation of DataChangeListenerRegistration and related classes"
authorEd Warnicke <eaw@cisco.com>
Thu, 3 Jul 2014 21:00:34 +0000 (21:00 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 3 Jul 2014 21:00:34 +0000 (21:00 +0000)
91 files changed:
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java
opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java [moved from opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBean.java with 87% similarity]
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java
opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java
opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java
opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java
opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java
opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java
opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModuleFactory.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModuleFactory.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java [deleted file]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/MountPointImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java
opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang
opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java
opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java
opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java
opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html
opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreSnapshotImpl.java
opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/AbstractNetconfSessionNegotiator.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronNetwork.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronPort.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronRouter.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java [deleted file]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java [new file with mode: 0644]

index fef2c7196948c007705b4444a5c9445065618648..a62bd7da06501b355c41f36230dbf30a982d61fa 100644 (file)
@@ -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<S extends ProtocolSession<?>, L extends
      *
      * @return ChannelFuture representing the binding process
      */
-    protected <CH extends Channel> ChannelFuture createServer(SocketAddress address, Class<? extends ServerChannel> channelClass,
-                                                              final ChannelPipelineInitializer<CH, S> initializer) {
+    protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address, final Class<? extends ServerChannel> channelClass,
+            final ChannelPipelineInitializer<CH, S> initializer) {
         final ServerBootstrap b = new ServerBootstrap();
         b.childHandler(new ChannelInitializer<CH>() {
 
@@ -110,6 +114,7 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, 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<S extends ProtocolSession<?>, L extends
     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
         final Bootstrap b = new Bootstrap();
         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<S>(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<SocketChannel>() {
-
                     @Override
                     protected void initChannel(final SocketChannel ch) {
                         initializer.initializeChannel(ch, p);
@@ -162,6 +166,18 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, 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;
@@ -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;
 
index dedeeed789f5e8b9ec030f2c349beec19f1c2872..ba6676b927bb554d296b2ebaa9efd3205bdebc4c 100644 (file)
@@ -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;
index 3e7b65e1bdcf8f25cfe6c255e43072edc2382f6a..8c132c93b298dee714f3efa063f329efc70a7878 100644 (file)
@@ -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;
index 549ff9ffcfdb9254a4115349d1cbd65520875809..559993f2648ec013791bdcf7167e412fe9a69102 100644 (file)
@@ -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> T newMBeanProxy(ObjectName on, Class<T> 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> T newMXBeanProxy(ObjectName on, Class<T> 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);
     }
-
 }
index 4adc0d9364e3392969c0c771edc4fd5ae41cdaf1..4cf766a8120ef4c559eb45a9883c7583c1983f8b 100644 (file)
@@ -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> T newMXBeanProxy(ObjectName on, Class<T> 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> T newMBeanProxy(ObjectName on, Class<T> clazz) {
         return JMX.newMBeanProxy(configMBeanServer, on, clazz);
     }
index ae064001956b9217fcfc1e950309ff514d17ddf6..775fa9fc20d97b10a48859703a4572f03b65d2ca 100644 (file)
@@ -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);
-    }
-
 }
index 89f3a4a51923a3f126f09b50af7e0d14b7af62a3..d8c5a56fb7a7561de457894180ad1a1b418b7f57 100644 (file)
@@ -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<QName, ServiceInterfaceEntry> qNamesToSIEs) {
+    public ModuleMXBeanEntryBuilder setqNamesToSIEs(final Map<QName, ServiceInterfaceEntry> 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<String, ModuleMXBeanEntry> result) {
+    private static void cleanUpNulls(final Map<String, ModuleMXBeanEntry> result) {
         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
             ModuleMXBeanEntry module = entry.getValue();
             if (module.getAttributes() == null) {
@@ -160,14 +163,14 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private static void checkUnaugumentedIdentities(Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
+    private static void checkUnaugumentedIdentities(final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
         if (unaugmentedModuleIdentities.size() > 0) {
             logger.warn("Augmentation not found for all currentModule identities: {}",
                     unaugmentedModuleIdentities.keySet());
         }
     }
 
-    private static void checkAttributeNamesUniqueness(Map<String, QName> uniqueGeneratedClassesNames, Map<String, ModuleMXBeanEntry> result) {
+    private static void checkAttributeNamesUniqueness(final Map<String, QName> uniqueGeneratedClassesNames, final Map<String, ModuleMXBeanEntry> result) {
         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
             checkUniqueRuntimeBeanAttributesName(entry.getValue(),
                     uniqueGeneratedClassesNames);
@@ -212,29 +215,30 @@ final class ModuleMXBeanEntryBuilder {
         return moduleIdentities;
     }
 
-    private Collection<ChoiceCaseNode> castChildNodesToChoiceCases(Set<DataSchemaNode> childNodes) {
+    private Collection<ChoiceCaseNode> castChildNodesToChoiceCases(final Set<DataSchemaNode> childNodes) {
         return Collections2.transform(childNodes, new Function<DataSchemaNode, ChoiceCaseNode>() {
             @Nullable
             @Override
-            public ChoiceCaseNode apply(@Nullable DataSchemaNode input) {
+            public ChoiceCaseNode apply(@Nullable final DataSchemaNode input) {
                 return (ChoiceCaseNode) input;
             }
         });
     }
 
-    private boolean areAllChildrenChoiceCaseNodes(Set<DataSchemaNode> childNodes) {
+    private boolean areAllChildrenChoiceCaseNodes(final Set<DataSchemaNode> childNodes) {
         for (DataSchemaNode childNode : childNodes) {
-            if (childNode instanceof ChoiceCaseNode == false)
+            if (childNode instanceof ChoiceCaseNode == false) {
                 return false;
+            }
         }
         return true;
     }
 
-    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> void processChoiceCaseNode(Map<String, ModuleMXBeanEntry> result,
-            Map<String, QName> uniqueGeneratedClassesNames, String configModulePrefix,
-            Map<String, IdentitySchemaNode> moduleIdentities,
-            Map<String, IdentitySchemaNode> unaugmentedModuleIdentities, AugmentationSchema augmentation,
-            DataSchemaNode when) {
+    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> void processChoiceCaseNode(final Map<String, ModuleMXBeanEntry> result,
+            final Map<String, QName> uniqueGeneratedClassesNames, final String configModulePrefix,
+            final Map<String, IdentitySchemaNode> moduleIdentities,
+            final Map<String, IdentitySchemaNode> 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<String, QName> uniqueGeneratedClassesNames,
-            DataSchemaNode when, Collection<RuntimeBeanEntry> runtimeBeans) {
+    private void checkUniqueRuntimeBeansGeneratedClasses(final Map<String, QName> uniqueGeneratedClassesNames,
+            final DataSchemaNode when, final Collection<RuntimeBeanEntry> 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<String, QName> uniqueGeneratedClassesNames) {
+    private static void checkUniqueRuntimeBeanAttributesName(final ModuleMXBeanEntry mxBeanEntry,
+            final Map<String, QName> 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<String, QName> uniqueGeneratedClassNames,
-            QName parentQName, Map<String, AttributeIfc> yangToAttributes) {
+    private void checkUniqueAttributesWithGeneratedClass(final Map<String, QName> uniqueGeneratedClassNames,
+            final QName parentQName, final Map<String, AttributeIfc> yangToAttributes) {
         for (Map.Entry<String, AttributeIfc> 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<String, QName> uniqueGeneratedClassNames, QName parentQName, TOAttribute attr) {
+    private void checkUniqueTOAttr(final Map<String, QName> 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<RuntimeBeanEntry> fillRuntimeBeans(DataNodeContainer dataNodeContainer, Module currentModule,
-            TypeProviderWrapper typeProviderWrapper, String packageName, String moduleLocalNameFromXPath,
-            String javaNamePrefix) {
+    private Collection<RuntimeBeanEntry> 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 extends DataNodeContainer & SchemaNode> HAS_CHILDREN_AND_QNAME getDataNodeContainer(ChoiceCaseNode choiceCaseNode) {
+    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> HAS_CHILDREN_AND_QNAME getDataNodeContainer(final ChoiceCaseNode choiceCaseNode) {
         Set<DataSchemaNode> 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<String, AttributeIfc> fillConfiguration(DataNodeContainer dataNodeContainer, Module currentModule,
-            TypeProviderWrapper typeProviderWrapper, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
-            SchemaContext schemaContext, String packageName) {
+    private Map<String, AttributeIfc> fillConfiguration(final DataNodeContainer dataNodeContainer, final Module currentModule,
+            final TypeProviderWrapper typeProviderWrapper, final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
+            final SchemaContext schemaContext, final String packageName) {
         Map<String, AttributeIfc> yangToAttributes = new HashMap<>();
         Set<DataSchemaNode> childNodes = dataNodeContainer.getChildNodes();
         for (DataSchemaNode attrNode : childNodes) {
@@ -411,8 +415,8 @@ final class ModuleMXBeanEntryBuilder {
         return yangToAttributes;
     }
 
-    private Map<String, QName> findProvidedServices(IdentitySchemaNode moduleIdentity, Module currentModule,
-            Map<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
+    private Map<String, QName> findProvidedServices(final IdentitySchemaNode moduleIdentity, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final SchemaContext schemaContext) {
         Map<String, QName> 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<QName, ServiceInterfaceEntry> qNamesToSIEs, TypeProviderWrapper typeProviderWrapper,
-            SchemaContext schemaContext, String packageName) {
+    private AttributeIfc getAttributeValue(final DataSchemaNode attrNode, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> 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<? extends AbstractDependencyAttribute> extractDependency(DataNodeContainer dataNodeContainer,
-            DataSchemaNode attrNode, Module currentModule, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
-            SchemaContext schemaContext) {
+    private Optional<? extends AbstractDependencyAttribute> extractDependency(final DataNodeContainer dataNodeContainer,
+            final DataSchemaNode attrNode, final Module currentModule, final Map<QName, ServiceInterfaceEntry> 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<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
+    private ServiceInterfaceEntry findSIE(final String prefixAndIdentityLocalName, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> 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();
index 5fea8fd078dfbbd95ead79b2610eb16e7bf0a4fe..ccd701d1fb36a2bba58093999a21aa23c7ac5c08 100644 (file)
@@ -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());
     }
 }
index c941d1504ddae409a9fdfa0c14ec4da957d1038e..23b071c817022ac0103f7cc01c4cc5f5482ba995 100644 (file)
@@ -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<Rpc> rpcs;
 
     @VisibleForTesting
-    RuntimeBeanEntry(String packageName,
-            DataNodeContainer nodeForReporting, String yangName,
-            String javaNamePrefix, boolean isRoot,
-            Optional<String> keyYangName, List<AttributeIfc> attributes,
-            List<RuntimeBeanEntry> children, Set<Rpc> rpcs) {
+    RuntimeBeanEntry(final String packageName,
+            final DataNodeContainer nodeForReporting, final String yangName,
+            final String javaNamePrefix, final boolean isRoot,
+            final Optional<String> keyYangName, final List<AttributeIfc> attributes,
+            final List<RuntimeBeanEntry> children, final Set<Rpc> 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<String, RuntimeBeanEntry> 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<QName, Set<RpcDefinition>> identitiesToRpcs = getIdentitiesToRpcs(currentModule);
 
@@ -151,7 +153,7 @@ public class RuntimeBeanEntry {
     }
 
     private static Map<QName/* of identity */, Set<RpcDefinition>> getIdentitiesToRpcs(
-            Module currentModule) {
+            final Module currentModule) {
         // currently only looks for local identities (found in currentModule)
         Map<QName, Set<RpcDefinition>> 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<QName, Set<RpcDefinition>> identitiesToRpcs) {
+            final String packageName, final DataNodeContainer subtree,
+            final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
+            final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
 
         List<AttributeIfc> attributes = Lists.newArrayList();
         // List<JavaAttribute> 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<RpcDefinition> 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<DataSchemaNode> sortAttributes(Set<DataSchemaNode> childNodes) {
+    private static Collection<DataSchemaNode> sortAttributes(final Set<DataSchemaNode> childNodes) {
         final TreeSet<DataSchemaNode> dataSchemaNodes = new TreeSet<>(new Comparator<DataSchemaNode>() {
             @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<QName, Set<RpcDefinition>> identitiesToRpcs) {
+    private static RuntimeBeanEntry createHierarchical(final String packageName,
+            final ListSchemaNode listSchemaNode,
+            final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
+            final Map<QName, Set<RpcDefinition>> 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<AttributeIfc> attributes, String javaNamePrefix,
-            List<RuntimeBeanEntry> children, Set<Rpc> rpcs) {
+    private static RuntimeBeanEntry createRoot(final String packageName,
+            final DataNodeContainer nodeForReporting, final String attributeYangName,
+            final List<AttributeIfc> attributes, final String javaNamePrefix,
+            final List<RuntimeBeanEntry> children, final Set<Rpc> rpcs) {
         return new RuntimeBeanEntry(packageName, nodeForReporting,
                 attributeYangName, javaNamePrefix, true,
                 Optional.<String> absent(), attributes, children, rpcs);
@@ -442,8 +447,8 @@ public class RuntimeBeanEntry {
         private final Set<Rpc> rpcs;
 
         public AttributesRpcsAndRuntimeBeans(
-                List<RuntimeBeanEntry> runtimeBeanEntries,
-                List<AttributeIfc> attributes, Set<Rpc> rpcs) {
+                final List<RuntimeBeanEntry> runtimeBeanEntries,
+                final List<AttributeIfc> attributes, final Set<Rpc> 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<JavaAttribute> parameters) {
+        Rpc(final AttributeIfc returnType, final String name, final String yangName,
+                final List<JavaAttribute> 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;
     }
 
index dd44246867abb9af1e51bfe1bc5dbd8ea8c63f91..fab273c60093b529931e5f0ce4f02f9198327ff7 100644 (file)
@@ -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<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
                 .create(jmxImplModule, modulesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context))
-                        , PACKAGE_NAME);
+                , PACKAGE_NAME);
         Map<String, AttributeIfc> 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<String, ModuleMXBeanEntry> namesToMBEs, Map<String, AttributeIfc> attributes) {
+    private void assertCorrectAttributesSize(final Map<String, ModuleMXBeanEntry> namesToMBEs, final Map<String, AttributeIfc> 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<RuntimeBeanEntry> runtimeBeans, String yangName) {
+            final Collection<RuntimeBeanEntry> 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"));
index eed86951033bc5ec2aa5251e4f187ea0f0f3c1a9..f22edbf948f0ba93b77346cc0b55786fcc032ab5 100644 (file)
@@ -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,}", " ");
     }
 }
index 7b1df982471006c073b6b1b4b654149cc665bedc..afeddbfaabc6283fa9352cc543e23db43310871e 100644 (file)
                         <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
                         <name>binding-data-broker</name>
                     </data-broker>
+                    <root-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                        <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-async-data-broker</type>
+                        <name>binding-data-broker</name>
+                    </root-data-broker>
                 </module>
 
 
index 5959d233669264d98d904a1eca891aa2024854b5..e2c13867754d187f26f9f9a1dc4414a2b4114572 100644 (file)
@@ -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<? extends Object> nodeConnectorIdentifier) {
-        final List<PathArgument> path = nodeConnectorIdentifier.getPath();
-        if (path.size() >= 3) {
-            final PathArgument nodePath = path.get(1);
-            final PathArgument nodeConnectorPath = path.get(2);
-            final List<PathArgument> nodeConnectors = nodeToNodeConnectorsMap.get(nodePath);
-            if (nodeConnectors != null) {
-                return nodeConnectors.contains(nodeConnectorPath);
-            }
+        final Iterator<PathArgument> 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<PathArgument> nodeConnectors = nodeToNodeConnectorsMap.get(nodePath);
+        return nodeConnectors == null ? false :
+            nodeConnectors.contains(nodeConnectorPath);
     }
 
     private boolean recordNodeConnector(final InstanceIdentifier<? extends Object> nodeConnectorIdentifier) {
-        final List<PathArgument> path = nodeConnectorIdentifier.getPath();
-        if (path.size() < 3) {
+        final Iterator<PathArgument> 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<PathArgument> nodeConnectors = this.nodeToNodeConnectorsMap.get(nodePath);
@@ -766,6 +788,6 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI
     }
 
     private List<PathArgument> removeNodeConnectors(final InstanceIdentifier<? extends Object> nodeIdentifier) {
-        return this.nodeToNodeConnectorsMap.remove(nodeIdentifier.getPath().get(1));
+        return this.nodeToNodeConnectorsMap.remove(Iterables.get(nodeIdentifier.getPathArguments(), 1));
     }
 }
index 17cd67a8576018485d3f1162dab89d51be0fcf15..018e26878c9873490d6c3ed88822edb78efe0280 100644 (file)
@@ -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<ProviderFunctionality> getProviderFunctionality() {
index 763e6ad3ca92e40e02a6e3c63a1ad2e96d46d747..a7c8843fcf3c48d1aa79fd85fbcc798a7b7c3efe 100644 (file)
@@ -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;
-    }
 }
index 188272fb60c186f07b472805776df83ee12899e0..61e7a2e6a240d9e7ab98574f7dd1bee2058ed987 100644 (file)
@@ -1,96 +1,85 @@
-/*\r
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-/**\r
- * Generated file\r
-\r
- * Generated from: yang module name: opendaylight-sal-binding-broker-impl  yang module local name: binding-broker-impl\r
- * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator\r
- * Generated at: Wed Nov 20 17:33:01 CET 2013\r
- *\r
- * Do not modify this file unless it is present under src/main directory\r
- */\r
-package org.opendaylight.controller.config.yang.md.sal.binding.impl;\r
-\r
-import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;\r
-import org.opendaylight.controller.sal.binding.impl.RootBindingAwareBroker;\r
-import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;\r
-import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl;\r
-import org.opendaylight.controller.sal.binding.impl.forward.DomForwardingUtils;\r
-import org.osgi.framework.BundleContext;\r
-\r
-/**\r
-*\r
-*/\r
-public final class BindingBrokerImplModule extends\r
-        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModule {\r
-\r
-    private BundleContext bundleContext;\r
-\r
-    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {\r
-        super(identifier, dependencyResolver);\r
-    }\r
-\r
-    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,\r
-            final BindingBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) {\r
-        super(identifier, dependencyResolver, oldModule, oldInstance);\r
-    }\r
-\r
-    @Override\r
-    public void validate() {\r
-        super.validate();\r
-    }\r
-\r
-    @Override\r
-    public java.lang.AutoCloseable createInstance() {\r
-\r
-        RootBindingAwareBroker broker;\r
-        if (DomForwardingUtils.isDomForwardedBroker(getDataBrokerDependency())) {\r
-            broker = createForwardedBroker();\r
-        } else {\r
-            broker = createStandaloneBroker();\r
-        }\r
-        broker.start();\r
-        return broker;\r
-    }\r
-\r
-    private RootBindingAwareBroker createStandaloneBroker() {\r
-        RootBindingAwareBroker broker = new RootBindingAwareBroker(getIdentifier().getInstanceName());\r
-\r
-        broker.setLegacyDataBroker(getDataBrokerDependency());\r
-        broker.setNotificationBroker(getNotificationServiceDependency());\r
-        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));\r
-        // FIXME: Also set Async Data Broker\r
-        return broker;\r
-    }\r
-\r
-    private RootBindingAwareBroker createForwardedBroker() {\r
-        DomForwardedBindingBrokerImpl broker = new DomForwardedBindingBrokerImpl(getIdentifier().getInstanceName());\r
-\r
-        broker.setLegacyDataBroker(getDataBrokerDependency());\r
-        broker.setNotificationBroker(getNotificationServiceDependency());\r
-        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));\r
-\r
-        broker.getMountManager().setDataCommitExecutor(SingletonHolder.getDefaultCommitExecutor());\r
-        broker.getMountManager().setNotificationExecutor(SingletonHolder.getDefaultNotificationExecutor());\r
-\r
-        // FIXME: Also set Async Data Broker\r
-        DomForwardingUtils.reuseForwardingFrom(broker, broker.getDataBroker());\r
-        broker.startForwarding();\r
-        return broker;\r
-    }\r
-\r
-    public BundleContext getBundleContext() {\r
-        return bundleContext;\r
-    }\r
-\r
-    public void setBundleContext(final BundleContext bundleContext) {\r
-        this.bundleContext = bundleContext;\r
-    }\r
-}\r
+/*
+ * 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;
+    }
+}
index a11a7d67f5d4077006676dc476cf154e1de8ade8..181b568cf51e898a807053dbe16ab353fdfab2de 100644 (file)
 */
 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;
-    }
-
 }
index 7357926b9e6226a612bd0fc453dc28b737cff5b8..4a4e8000781381f906888369a8db0ac6b683e525 100644 (file)
@@ -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;\r
-\r
+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;
-\r
-/**\r
-*\r
-*/\r
-public final class DataBrokerImplModule extends\r
-        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModule {\r
-\r
-    private BundleContext bundleContext;\r
-\r
-    public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {\r
-        super(identifier, dependencyResolver);\r
-    }\r
-\r
-    public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,\r
-            DataBrokerImplModule oldModule, java.lang.AutoCloseable oldInstance) {\r
-        super(identifier, dependencyResolver, oldModule, oldInstance);\r
-    }\r
-\r
-    @Override\r
-    public void validate() {\r
-        super.validate();\r
-    }\r
-\r
-    @Override\r
-    public java.lang.AutoCloseable createInstance() {\r
-        RootDataBrokerImpl dataBindingBroker;\r
-\r
-\r
-        ExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor();\r
-        BindingIndependentMappingService potentialMapping = resolveMappingServiceDependency();\r
-        if (getDomBrokerDependency() != null && potentialMapping != null) {\r
-\r
-            dataBindingBroker = createDomConnectedBroker(listeningExecutor,potentialMapping);\r
-        } else {\r
-            dataBindingBroker = createStandAloneBroker(listeningExecutor);\r
-        }\r
-        dataBindingBroker.registerRuntimeBean(getRootRuntimeBeanRegistratorWrapper());\r
-        dataBindingBroker.setNotificationExecutor(SingletonHolder.getDefaultChangeEventExecutor());\r
-        return dataBindingBroker;\r
-    }\r
-    private BindingIndependentMappingService resolveMappingServiceDependency() {\r
-        if(getMappingService() != null) {\r
-            return getMappingServiceDependency();\r
-        }\r
-\r
-        ServiceReference<BindingIndependentMappingService> potentialMappingService = bundleContext.getServiceReference(BindingIndependentMappingService.class);\r
-        if(potentialMappingService != null) {\r
-            return bundleContext.getService(potentialMappingService);\r
-        }\r
-        return null;\r
-    }\r
-\r
-    private RootDataBrokerImpl createStandAloneBroker(ExecutorService listeningExecutor) {\r
-        RootDataBrokerImpl broker = new RootDataBrokerImpl();\r
-        broker.setExecutor(listeningExecutor);\r
-        return broker;\r
-    }\r
-\r
-    private RootDataBrokerImpl createDomConnectedBroker(ExecutorService listeningExecutor, BindingIndependentMappingService mappingService) {\r
-        DomForwardedDataBrokerImpl forwardedBroker = new DomForwardedDataBrokerImpl();\r
-        forwardedBroker.setExecutor(listeningExecutor);\r
-        BindingIndependentConnector connector = BindingDomConnectorDeployer.createConnector(mappingService);\r
-        getDomBrokerDependency().registerProvider(forwardedBroker, getBundleContext());\r
-        ProviderSession domContext = forwardedBroker.getDomProviderContext();\r
-        forwardedBroker.setConnector(connector);\r
-        forwardedBroker.setDomProviderContext(domContext);\r
-        forwardedBroker.startForwarding();\r
-        return forwardedBroker;\r
-    }\r
-\r
-    public BundleContext getBundleContext() {\r
-        return bundleContext;\r
-    }\r
-\r
-    public void setBundleContext(BundleContext bundleContext2) {\r
-        this.bundleContext = bundleContext2;\r
-    }\r
-}\r
+
+/**
+*
+*/
+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;
+    }
+
+}
index 9ce3ebf73f26793089c171126e33db8c6d3d956d..d3fc5ac215d7c201e66e9dfdf6022cc12d1fe3eb 100644 (file)
@@ -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;
-    }
-
 }
index 7467e544fdc8e2577447da8c62fca6319b7e3d0c..0ea30f7e66a817f63c63cc81e20f3890170ea7b5 100644 (file)
@@ -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) {
 
index f01977503e8239128ac5b3bb022d6c4278bc863b..5b5fb45fd9904eb80ece3e9de0faa56351f6f796 100644 (file)
@@ -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;
-    }
-
 }
index 003f57cd72f053557a79fa761896894836ced89e..6b519955accd308109657dcb44823e4bca3d595d 100644 (file)
@@ -120,7 +120,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
      */
     public Optional<InstanceIdentifier<? extends DataObject>> 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<InstanceIdentifier<? extends DataObject>> toBindingAugmented(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
         Optional<InstanceIdentifier<? extends DataObject>> 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.<PathArgument> 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<InstanceIdentifier<? extends DataObject>> 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<Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
             final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
         Optional<InstanceIdentifier<? extends DataObject>> potentialPath = toBinding(normalized.getKey());
         if (potentialPath.isPresent()) {
             InstanceIdentifier<? extends DataObject> bindingPath = potentialPath.get();
@@ -375,18 +373,18 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
             try {
                 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
                         new Supplier<Class>() {
-                            @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;
index 4456dea77f98fad1f4f43c79f67b224d9e44990e..cee4b1efb3a3107e27fa5325dd6d3f92cc937609 100644 (file)
@@ -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;
+                    }
+                }
+            }
         }
     }
 
index 623b2fdd6365c5f14d3948d2b567ab65c81435cd..1ea56381ef1cf9a4b248d2be2795d6c290f81c0d 100644 (file)
@@ -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<BrokerService> services = MutableClassToInstanceMap.create();
+        biBrokerImpl = new BrokerImpl(router,services);
 
     }
 
index 7ce475dd59ea1a056ac8d5a85d751a33f6d9a17f..2b9694bed71d87dfb8d48e04024b94f619e5c049 100644 (file)
@@ -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<T extends PathArgument> impleme
     }
 
     private static abstract class CompositeNodeNormalizationOperation<T extends PathArgument> extends
-            DataNormalizationOperation<T> {
+    DataNormalizationOperation<T> {
 
         protected CompositeNodeNormalizationOperation(final T identifier) {
             super(identifier);
@@ -218,7 +220,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static abstract class DataContainerNormalizationOperation<T extends PathArgument> extends
-            CompositeNodeNormalizationOperation<T> {
+    CompositeNodeNormalizationOperation<T> {
 
         private final DataNodeContainer schema;
         private final Map<QName, DataNormalizationOperation<?>> byQName;
@@ -276,7 +278,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static final class ListItemNormalization extends
-            DataContainerNormalizationOperation<NodeIdentifierWithPredicates> {
+    DataContainerNormalizationOperation<NodeIdentifierWithPredicates> {
 
         private final List<QName> keyDefinition;
 
@@ -356,7 +358,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static abstract class MixinNormalizationOp<T extends PathArgument> extends
-            CompositeNodeNormalizationOperation<T> {
+    CompositeNodeNormalizationOperation<T> {
 
         protected MixinNormalizationOp(final T identifier) {
             super(identifier);
@@ -615,25 +617,25 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
     private static class AnyXmlNormalization extends DataNormalizationOperation<NodeIdentifier> {
 
-        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<NodeIdentifier, Node<?>, 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<T extends PathArgument> impleme
         }
 
         @Override
-        public NormalizedNode<?, ?> createDefault( PathArgument currentArg ) {
+        public NormalizedNode<?, ?> createDefault( final PathArgument currentArg ) {
             return null;
         }
     }
@@ -694,7 +696,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> 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) {
index ec8ce6ecd5a96e628d2883ab38f24aaab383095a..113d3dc9f762ec1f0f2f6d4c7307ae3f04e0d19b 100644 (file)
@@ -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<PathArgument> normalizedArgs = ImmutableList.builder();
 
         DataNormalizationOperation<?> currentOp = operation;
-        Iterator<PathArgument> arguments = legacy.getPath().iterator();
+        Iterator<PathArgument> 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<InstanceIdentifier, NormalizedNode<?, ?>> 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<PathArgument> 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<PathArgument> 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) {
index ce861f7e7afbb4884fbf9ddbc8979eb0a1a3a64e..dcb90a83ba1e3b15284b9a7d8d8bcabacf99cb3b 100644 (file)
@@ -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<LegacyNodeData>() {
             @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<Node<?>>() {
             @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<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> 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<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME);
@@ -649,7 +652,7 @@ public class DataNormalizerTest {
         testBuilder.add(outerContBuilder.toInstance());
 
         Entry<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> 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<InstanceIdentifier, CompositeNode>(
-                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<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> 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));
     }
 }
index 767785dbf13c1dac1231b46e2339f044ebe0cb97..998d884b0cde71cd2fe774352229a61afd98761d 100644 (file)
@@ -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<BrokerService> 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;
     }
 }
index 38f5009feb85e14376755f71008425d137c8cd00..f1fcb495aace6a38ade530efa34b32eba817772f 100644 (file)
@@ -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;
-    }
-
 }
index d3852d28c5ba1ff9d6191f135cbcaba0c88ad2b4..69b17ee3c48aeb5aae64dc8c4b02e36abdfce7a7 100644 (file)
@@ -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<String, String>());
-
-
         return newDataBroker;
     }
-
-    private BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    void setBundleContext(final BundleContext ctx) {
-        bundleContext = ctx;
-    }
 }
index 91d42c48c13577853ecbc7d3a618bf0b2de93f4e..56a51ed45e75588d40adca6b9613348e3e1c8d9a 100644 (file)
@@ -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;
-    }
 }
index fd24944018c69b3b9480a7018e0fea1c23986719..fbc418dc2aec0203d4f52ad6b7ace8cc083ca019 100644 (file)
@@ -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<SchemaService> 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<SchemaService> {
 
-        private BundleContext bundleContext;
-        private ServiceReference<SchemaService> reference;
         private SchemaService delegate;
 
-        public GlobalSchemaServiceProxy(final BundleContext bundleContext, final ServiceReference<SchemaService> 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;
             }
         }
 
index 5b34fba69ac1b0eaebabaf8a82c801082eacc864..f361af948cb1c600a1c778fe97958cbcef1643d0 100644 (file)
@@ -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<SchemaServiceListener> 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);
+        }
+
+    }
 }
index b3fb7b6da8be09d67c0b7244f50f99c093a8173b..27e322f23baf265a046d04317f2bfbf78ab2f74c 100644 (file)
@@ -43,7 +43,7 @@ import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.ListenableFuture;
 
 public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransaction> implements
-        DataModificationTransaction, Delegator<T> {
+DataModificationTransaction, Delegator<T> {
 
     private static final Logger LOG = LoggerFactory.getLogger(BackwardsCompatibleTransaction.class);
 
@@ -228,23 +228,23 @@ public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransa
 
             LOG.trace("write {}:{} ",store,normalizedPath);
             try {
-            List<PathArgument> currentArguments = new ArrayList<>();
-            DataNormalizationOperation<?> currentOp = getNormalizer().getRootOperation();
-            Iterator<PathArgument> 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<PathArgument> currentArguments = new ArrayList<>();
+                DataNormalizationOperation<?> currentOp = getNormalizer().getRootOperation();
+                Iterator<PathArgument> 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 (file)
index 3291afa..0000000
+++ /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<DataBrokerService> dataReg = null;
-    private ServiceRegistration<DataProviderService> dataProviderReg = null;
-    private ServiceRegistration<MountService> mountReg = null;
-    private ServiceRegistration<MountProvisionService> mountProviderReg = null;
-    private SchemaService schemaService = null;
-    private ServiceRegistration<RpcProvisionRegistry> 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<String, String> emptyProperties = new Hashtable<String, String>();
-        broker.setBundleContext(context);
-
-        final ServiceReference<SchemaService> serviceRef = context
-                .getServiceReference(SchemaService.class);
-        schemaService = context.<SchemaService> 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;
-    }
-}
index e4bd0343cfcf62999d3becca52177eaf8d366bcd..1af03e50465e2acc922f19ad66f15a3c640bfc34 100644 (file)
@@ -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<ProviderContextImpl> providerSessions = Collections
             .synchronizedSet(new HashSet<ProviderContextImpl>());
 
-    private BundleContext bundleContext = null;
-
     private AutoCloseable deactivator = null;
 
     private RpcRouter router = null;
 
+    private final ClassToInstanceMap<BrokerService> services;
+
+    public  BrokerImpl(final RpcRouter router,final ClassToInstanceMap<BrokerService> 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 <T extends BrokerService> Optional<T> getGlobalService(final Class<T> service) {
+        return Optional.fromNullable(services.getInstance(service));
+    }
+
 }
index fa81bc9040849c6b198187c4d846de308bfbe685..e96b242720e88bbabe918cbde127af6eb0b3d5e8 100644 (file)
@@ -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<BrokerService> 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<RpcResult<CompositeNode>> rpc(final QName rpc,
             final CompositeNode input) {
+        checkNotClosed();
         return broker.invokeRpcAsync(rpc, input);
     }
 
     @Override
     public <T extends BrokerService> T getService(final Class<T> service) {
+        checkNotClosed();
         final T localProxy = instantiatedServices.getInstance(service);
         if (localProxy != null) {
             return localProxy;
         }
-        final ServiceReference<T> 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<T> 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.");
+    }
 }
index 430963a884b4fbaa71a7c3c12d5df9356058be0c..60a7e81c4c046183e6ee59e0f27d48e5a15e90bc 100644 (file)
@@ -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<SchemaServiceListener, SchemaServiceListener> listenerTracker;
     private BundleTracker<Iterable<Registration<URL>>> 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<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+    public synchronized ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
         Optional<SchemaContext> 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<SchemaServiceListener> listener : listeners) {
             try {
@@ -194,7 +213,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
+    public synchronized SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
 
         SchemaServiceListener listener = context.getService(reference);
         SchemaContext _ctxContext = getGlobalContext();
index 623bbdb19514ce15ffa0b9102959fbac77cb51d2..e69343d4fe82c7f36a7a9c378c8669e67cb1114b 100644 (file)
@@ -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<NotificationListener> addNotificationListener(QName notification, NotificationListener listener) {
+    public Registration<NotificationListener> 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<DataReader<InstanceIdentifier, CompositeNode>> registerOperationalReader(
-            InstanceIdentifier path, DataReader<InstanceIdentifier, CompositeNode> reader) {
+            final InstanceIdentifier path, final DataReader<InstanceIdentifier, CompositeNode> reader) {
         return dataReader.registerOperationalReader(path, reader);
     }
 
     @Override
     public Registration<DataReader<InstanceIdentifier, CompositeNode>> registerConfigurationReader(
-            InstanceIdentifier path, DataReader<InstanceIdentifier, CompositeNode> reader) {
+            final InstanceIdentifier path, final DataReader<InstanceIdentifier, CompositeNode> 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<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode input) {
         return rpcs.invokeRpc(rpc, input);
     }
 
     @Override
-    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(RpcRegistrationListener listener) {
+    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(final RpcRegistrationListener listener) {
         return rpcs.addRpcRegistrationListener(listener);
     }
 
     @Override
-    public ListenableFuture<RpcResult<CompositeNode>> rpc(QName type, CompositeNode input) {
+    public ListenableFuture<RpcResult<CompositeNode>> 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<DataChangeListener> registerDataChangeListener(InstanceIdentifier path,
-            DataChangeListener listener) {
+    public ListenerRegistration<DataChangeListener> registerDataChangeListener(final InstanceIdentifier path,
+            final DataChangeListener listener) {
         return dataReader.registerDataChangeListener(path, listener);
     }
 
     @Override
     public Registration<DataCommitHandler<InstanceIdentifier, CompositeNode>> registerCommitHandler(
-            InstanceIdentifier path, DataCommitHandler<InstanceIdentifier, CompositeNode> commitHandler) {
+            final InstanceIdentifier path, final DataCommitHandler<InstanceIdentifier, CompositeNode> 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<InstanceIdentifier, CompositeNode> {
-
-
-        private InstanceIdentifier shortenPath(InstanceIdentifier path) {
+        private InstanceIdentifier shortenPath(final InstanceIdentifier path) {
             InstanceIdentifier ret = null;
             if(mountPath.contains(path)) {
                 List<PathArgument> 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<RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>>> registerCommitHandlerListener(
-            RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>> commitHandlerListener) {
+            final RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>> commitHandlerListener) {
         return dataReader.registerCommitHandlerListener(commitHandlerListener);
     }
 
     @Override
     public <L extends RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> ListenerRegistration<L> registerRouteChangeListener(
-            L listener) {
+            final L listener) {
         return rpcs.registerRouteChangeListener(listener);
     }
 }
index 5e8c0e82538b4d2beacddd3366571ac2a734f7c5..b8bb279297cf835cb185d909d6eaf280dccc59d7 100644 (file)
@@ -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<RpcRegistrationWrapper> 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<QName> getSupportedRpcs() {
-        return getBroker().getRouter().getSupportedRpcs();
+        return getBrokerChecked().getRouter().getSupportedRpcs();
     }
 
     @Override
     public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(
             final RpcRegistrationListener listener) {
-        return getBroker().getRouter().addRpcRegistrationListener(listener);
+        return getBrokerChecked().getRouter().addRpcRegistrationListener(listener);
     }
 
     /**
index ba9b2b7f55964d90023532082bc41767f037daa4..4b5b86d0dafd2cc08df1f7c9a31086350e3b3512 100644 (file)
@@ -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<InstanceIdentifier, CompositeNode> {
     private final static Logger LOG = LoggerFactory
@@ -46,7 +46,7 @@ AbstractDataReadRouter<InstanceIdentifier, CompositeNode> {
     @Override
     protected CompositeNodeTOImpl merge(final InstanceIdentifier path,
             final Iterable<CompositeNode> 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<Node<?>> nodes = new ArrayList<Node<?>>();
index 1a572d157dba9f8272140495b8eabf9669df11bc..3cd7ed5e13ed16b2449f2386604aa81802679b17 100644 (file)
@@ -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<DataStore> 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;
index 853e3e391f591a8b3d6c5aad72d5d62da0093471..8d33ff7997dab4b2a09d813c9200e8b95f7dc762 100644 (file)
@@ -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<T extends BrokerService> implem
     private T delegate;
     private final ServiceReference<T> reference;
 
-    public AbstractBrokerServiceProxy(final ServiceReference<T> ref, final T delegate) {
+    public AbstractBrokerServiceProxy(final @Nullable ServiceReference<T> 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() {
index f893f96d18c59e94df9fe7961b8856b214a6f196..113a9c08dbe064f2d8d2066ee94dd8a1e0952505 100644 (file)
@@ -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<String,String>());
     }
index 0f8ce1d95d31f727c018a9f801dca421c73f8a32..5adf39142ec5ee2af194b921a76b2ce01031ffd5 100644 (file)
@@ -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<Map<QName, Object>, CompositeNode> originalMap = YangDataUtils
-                .toIndexMap((List) original, node.getKeyDefinition());
+        .toIndexMap((List) original, node.getKeyDefinition());
         @SuppressWarnings({ "unchecked", "rawtypes" })
         final Map<Map<QName, Object>, CompositeNode> modifiedMap = YangDataUtils
-                .toIndexMap((List) modified, node.getKeyDefinition());
+        .toIndexMap((List) modified, node.getKeyDefinition());
 
         final List<Node<?>> mergedNodes = new ArrayList<Node<?>>(
                 original.size() + modified.size());
@@ -140,7 +140,7 @@ public class YangDataOperations {
                 modified.getNodeType()));
 
         final List<Node<?>> mergedChildNodes = new ArrayList<Node<?>>(stored
-                .getChildren().size() + modified.getChildren().size());
+                .getValue().size() + modified.getValue().size());
         final Set<QName> toProcess = new HashSet<QName>(stored.keySet());
         toProcess.addAll(modified.keySet());
 
index 306cd34a69502187084bec2a33643cac5231e979..29392dc7b3e91e6c6dbe202cbe1b4e4292cce17d 100644 (file)
@@ -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<PathArgument, QName> QNAME_FROM_PATH_ARGUMENT = new Function<PathArgument, QName>(){
@@ -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<QName> path) {
index 82897b0198cbf183953f2051f87c8fcfe9f030a8..a0ee5c50c93bc8a576c2d71b2dd7b37b86cda896 100644 (file)
@@ -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;
+                    }
+                }
             }
         }
     }
index e6221f6920152aab2d60936af78646c3dd394ea2..9d04a1b6ed039043a7737699b4c3bf88a5a91ef7 100644 (file)
@@ -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);
             }
 
index 2909baccdb0dd0bc8a23e80553a6914c3dd13fe6..3535c96c804e7a97aa7aad1c516dfa224819a95d 100644 (file)
@@ -74,7 +74,7 @@ public final class NetconfDeviceDataReader implements DataReader<InstanceIdentif
     private static Node<?> 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) {
index 1a3b108f8be7bb0d0748ff6e9db949d6fdfe8bc2..1737b8234a610267c9aa7f82eddd7a1f9912f502 100644 (file)
@@ -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<String> defaultOperation) {
+    private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional<String> defaultOperation) {
         final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
 
         // Target
@@ -133,8 +136,8 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
     }
 
     private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<String> operation,
-                                                    final Optional<CompositeNode> lastChildOverride) {
-        Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath);
+            final Optional<CompositeNode> lastChildOverride) {
+        Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
 
         List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
 
index ee6daa1e3d0dd81d60ca7c298402d837dbc6a457..0ea3d6a35ac74c873d3965a3a1d90e7c514aa99b 100644 (file)
@@ -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<String,String> errorInfo = ImmutableMap.<String,String>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<String, String> errorInfo = ex.getErrorInfo();
@@ -134,44 +135,45 @@ public class NetconfMessageTransformUtil {
         {
             for( Entry<String,String> e: errorInfo.entrySet() ) {
                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
-                           .append( "</" ).append( e.getKey() ).append( '>' );
+                .append( "</" ).append( e.getKey() ).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<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
index 696bf715355e402a0932532a36cde8e795a08236..85b4b2dee071aff3be08fb82b11690a8793d7014 100644 (file)
@@ -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<QName> foundLists = new HashSet<>();
 
         Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
-                                   Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
+                Collections.<DataSchemaNode>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<SimpleNode<?>> 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<CompositeNode> nodeList = parent.getCompositesByName( node.getNodeType() );
             if( nodeList.size() == 1 ) {
@@ -178,11 +178,12 @@ class JsonMapper {
         }
     }
 
-    private DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
+    private static DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> 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);
index 1f7b061e921cd057d13ece0002e998973fb66db2..e94554061800cb8ae918dc59a598fea980cac972 100644 (file)
@@ -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<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
         if (entrySetsOfRootJsonObject.size() != 1) {
             throw new UnsupportedFormatException("Json Object should contain one element");
-        } else {
-            Entry<String, JsonElement> 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<String, JsonElement> 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<String, JsonElement> 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<String> 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<String> 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) {
index 856e09fabd21a1083cbe716890ba22ae3b2d5bc6..9e6966540534c9c79d2a120f89c35ebf603d956d 100644 (file)
@@ -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<CompositeNode> {
     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<CompositeNode> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
-            throws IOException, WebApplicationException {
-        JsonReader jsonReader = new JsonReader();
+    public CompositeNode readFrom(final Class<CompositeNode> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType, final MultivaluedMap<String, String> 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);
         }
     }
 
index 290d976b2857c493e7c638592e2715e963a03277..cd263d3c55b0a56ce40feca32690749bd489ed6e 100644 (file)
@@ -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<Predicate> toPredicates(String predicatesStr, PrefixesMaping prefixMap) {
+    private static List<Predicate> toPredicates(final String predicatesStr, final PrefixesMaping prefixMap) {
         List<Predicate> result = new ArrayList<>();
         List<String> 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;
         }
     }
index 5f6909cea8e3e15d2b7887fe975d2d3e613163b5..0854ca71673465e76e7659bfa9479afc3fb1962f 100644 (file)
@@ -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<Restco
     private Object toJsonResponseBody( final ImmutableCompositeNode errorsNode,
             final DataNodeContainer errorsSchemaNode ) {
 
-        JsonMapper jsonMapper = new JsonMapper();
+        JsonMapper jsonMapper = new JsonMapper(null);
 
         Object responseBody = null;
         try {
             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-            JsonWriter writer = new JsonWriter( new OutputStreamWriter( outStream, "UTF-8" ) );
+            JsonWriter writer = new JsonWriter(new OutputStreamWriter( outStream, Charsets.UTF_8));
             writer.setIndent( "    " );
 
-            jsonMapper.write( writer, errorsNode, errorsSchemaNode, null );
+            jsonMapper.write( writer, errorsNode, errorsSchemaNode);
             writer.flush();
 
             responseBody = outStream.toString( "UTF-8" );
-        }
-        catch( IOException e ) {
+        } catch( IOException e ) {
             LOG.error( "Error writing error response body", e );
         }
 
@@ -239,13 +239,11 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
         try {
             doc = factory.newDocumentBuilder().parse(
                     new InputSource( new StringReader( errorInfoWithRoot ) ) );
-        }
-        catch( Exception e ) {
+        } catch( Exception e ) {
             // TODO: what if the content is text that happens to contain invalid markup? Could
             // wrap in CDATA and try again.
 
-            LOG.warn( "Error parsing restconf error-info, \"" + errorInfo + "\", as XML: " +
-                    e.toString() );
+            LOG.warn( "Error parsing restconf error-info, \"{}\", as XML", errorInfo, e);
             return null;
         }
 
index 422cf04cca82f7d0bf5d2f535df40a6f7688215e..1c2e9c5009897f741efaa6a1320665d7ba2a4b0a 100644 (file)
@@ -7,6 +7,9 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Charsets;
+import com.google.gson.stream.JsonWriter;
+
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
@@ -28,37 +31,35 @@ import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
-import com.google.gson.stream.JsonWriter;
-
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
-        Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
+    Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
     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<String, Object> 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<String, Object> 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();
     }
 
index bcb3c422ff8dc0c33c8a44d27d20b63ec1e3852d..e5a56cf47566c6ca4d3d8e1113b817706b404d71 100644 (file)
@@ -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<StructuredData> {
     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> TRANSFORMER = new ThreadLocal<Transformer>() {
+        @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<String, Object> 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<String, Object> 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);
         }
     }
 
index 96ad528a0dd3f9e0591b78b2be702e9b1d004c4c..69b975dab7e5ef15bb7e5ad4cf389ed55f0ef9c8 100644 (file)
@@ -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>, CompositeNode {
 
     private MutableCompositeNode compositeNode;
@@ -104,7 +104,7 @@ public final class CompositeNodeWrapper implements NodeWrapper<CompositeNode>, C
                 name = new QName(namespace, localName);
             }
 
-            List<Node<?>> nodeValues = new ArrayList<>();
+            List<Node<?>> nodeValues = new ArrayList<>(values.size());
             for (NodeWrapper<?> nodeWrapper : values) {
                 nodeValues.add(nodeWrapper.unwrap());
             }
index 6330c0a479caa5acf2926e5ce9820bc3a435e756..85c8e595396e9463b8fb7bf93437510041306b09 100644 (file)
@@ -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<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
 
     private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
@@ -129,10 +132,8 @@ public class ControllerContext implements SchemaContextListener {
             final boolean toMountPointIdentifier ) {
         this.checkPreconditions();
 
-        Iterable<String> split = Splitter.on( "/" ).split( restconfInstance );
-        final ArrayList<String> encodedPathArgs = Lists.<String> newArrayList( split );
-        final List<String> pathArgs = this.urlPathArgsDecode( encodedPathArgs );
-        this.omitFirstAndLastEmptyString( pathArgs );
+        final List<String> 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<String> omitFirstAndLastEmptyString( final List<String> list ) {
+    private static List<String> omitFirstAndLastEmptyString( final List<String> 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<PathArgument> elements = path.getPath();
+        final Iterable<PathArgument> 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<PathArgument> elements = path.getPath();
+        final Iterable<PathArgument> 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<QName, Object> map, final DataSchemaNode node,
@@ -839,20 +840,20 @@ public class ControllerContext implements SchemaContextListener {
 
     private static String toModuleName( final String str ) {
         Preconditions.<String> checkNotNull( str );
-        if( str.contains( ":" ) ) {
-            final String[] args = str.split( ":" );
-            if( args.length == 2 ) {
-                return args[0];
+        if( str.indexOf( ':' ) != -1 ) {
+            final Iterable<String> 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<String> 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<Module> modules = globalSchema.getModules();
 
         final Comparator<Module> comparator = new Comparator<Module>() {
@@ -916,7 +917,7 @@ public class ControllerContext implements SchemaContextListener {
         }
     }
 
-    public List<String> urlPathArgsDecode( final List<String> strings ) {
+    public static List<String> urlPathArgsDecode( final Iterable<String> strings ) {
         try {
             List<String> decodedPathArgs = new ArrayList<String>();
             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;
             }
         }
index 934d4434c38a3e724279405da05198099eba2f70..f93a0aea70fa311a7dd0b6f8ba520d8153f03b89 100644 (file)
@@ -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<?>>, Node<Void> {
 
     private Node<?> unwrapped;
@@ -31,17 +31,17 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
         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<?>>, Node<Void>
     }
 
     @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<?>>, Node<Void>
     }
 
     @Override
+    @Deprecated
     public CompositeNode getParent() {
         return unwrap().getParent();
     }
@@ -118,7 +119,7 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
     }
 
     @Override
-    public Void setValue(Void value) {
+    public Void setValue(final Void value) {
         return null;
     }
 
index 265cc5db4536c96ecbf51bf4005ff4ced54e8c14..14b8282312d7accd1ba0c912a55178c72d3f317c 100644 (file)
@@ -47,7 +47,7 @@ public class RestCodec {
     private RestCodec() {
     }
 
-    public static final Codec<Object, Object> from(TypeDefinition<?> typeDefinition, MountInstance mountPoint) {
+    public static final Codec<Object, Object> 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<String> {
 
         @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<PathArgument> 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<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
@@ -230,7 +229,7 @@ public class RestCodec {
         }
 
         @Override
-        public InstanceIdentifier deserialize(IdentityValuesDTO data) {
+        public InstanceIdentifier deserialize(final IdentityValuesDTO data) {
             List<PathArgument> result = new ArrayList<PathArgument>();
             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<Predicate> keyValuesToPredicateList(Map<QName, Object> keyValues) {
+        private List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
             List<Predicate> 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);
index 4716a02be2f26230721be7e08eb697eaeb0224cc..5a16c04aedb1fb7ed3d44b77bd1595897215d73f 100644 (file)
@@ -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<Node<?>> modulesAsData = new ArrayList<Node<?>>();
         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                        restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+                restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
 
         Set<Module> 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<Node<?>> streamsAsData = new ArrayList<Node<?>>();
         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<Node<?>> modulesAsData = new ArrayList<Node<?>>();
         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<Module> modules,
-                                                                 final MountInstance mountPoint) {
+            final MountInstance mountPoint) {
         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
         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<RpcDefinition> rpcs = module.getRpcs();
             for (final RpcDefinition rpc : rpcs) {
                 QName rpcQName = rpc.getQName();
                 SimpleNode<Object> immutableSimpleNode =
-                                     NodeFactory.<Object>createImmutableSimpleNode(rpcQName, null, null);
+                        NodeFactory.<Object>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<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
         List<DataSchemaNode> instanceDataChildrenByName =
                 this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode),
-                                                                       "name");
+                        "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         streamNodeValues.add(NodeFactory.<String>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.<String>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.<Boolean>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.<String>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.<String>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<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
         List<DataSchemaNode> instanceDataChildrenByName =
-            this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
+                this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         moduleNodeValues.add(NodeFactory.<String>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.<String>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.<String>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.<String>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<? extends Object> 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<String> streamNameNode = NodeFactory.<String>createImmutableSimpleNode(
-                             QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
+                QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
         final List<Node<?>> output = new ArrayList<Node<?>>();
         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<CompositeNode> rpcResult) {
+    private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
         if (rpcResult.isSuccessful() == false) {
 
             Collection<RpcError> 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<RestconfError> 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 extends Node<?>> T pruneDataAtDepth( T node, Integer depth ) {
+    private <T extends Node<?>> 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<RpcResult<TransactionStatus>> future =
-                                          broker.commitConfigurationDataPostBehindMountPoint(
-                                                       mountPoint, iiWithData.getInstanceIdentifier(), value);
+                        broker.commitConfigurationDataPostBehindMountPoint(
+                                mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
             else {
                 Future<RpcResult<TransactionStatus>> 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<TransactionStatus> status = null;
@@ -785,13 +790,13 @@ public class RestconfImpl implements RestconfService {
         try {
             if (mountPoint != null) {
                 Future<RpcResult<TransactionStatus>> future =
-                                             broker.commitConfigurationDataPostBehindMountPoint(
-                                                          mountPoint, iiWithData.getInstanceIdentifier(), value);
+                        broker.commitConfigurationDataPostBehindMountPoint(
+                                mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
             else {
                 Future<RpcResult<TransactionStatus>> 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<QName,Object> resolveKeysFromData(final ListSchemaNode listNode,
-                                                      final CompositeNode dataNode) {
+            final CompositeNode dataNode) {
         final HashMap<QName,Object> keyValues = new HashMap<QName, Object>();
         List<QName> _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<? extends Object> 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<NodeWrapper<?>> children = compositeNode.getValues();
         for( NodeWrapper<? extends Object> 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<? extends Object> 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<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
         for (final NodeWrapper<? extends Object> child : children) {
             final List<DataSchemaNode> 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<? extends Object> 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)*/ ) {
index 3131668ed9ed23ae8fb8f0edb75076c8635a235d..b0959c8398263dbd55a4ccb9fafac6d339f9fdaf 100644 (file)
@@ -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<?>>, SimpleNode<Object> {
 
     private SimpleNode<Object> simpleNode;
@@ -27,18 +27,18 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, 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<SimpleNode<?>>, 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<SimpleNode<?>>, Simp
             localName = null;
             name = null;
         }
-        return (SimpleNode<Object>) simpleNode;
+        return simpleNode;
     }
 
     @Override
@@ -98,6 +98,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
+    @Deprecated
     public CompositeNode getParent() {
         return unwrap().getParent();
     }
@@ -108,6 +109,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
+    @Deprecated
     public ModifyAction getModificationAction() {
         return unwrap().getModificationAction();
     }
@@ -123,7 +125,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
-    public Object setValue(Object value) {
+    public Object setValue(final Object value) {
         return unwrap().setValue(value);
     }
 
index 6282f37602be8236a737fe3e8ef42852816756bc..925a09337ca3ee1e8fba707020e3c7a19b8e03f6 100644 (file)
@@ -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<InstanceIdentifier, CompositeNode> change) {
+            final DataChangeEvent<InstanceIdentifier, CompositeNode> 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<InstanceIdentifier, CompositeNode> change) {
+            final DataChangeEvent<InstanceIdentifier, CompositeNode> 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<InstanceIdentifier, CompositeNode> change) {
+    private void addValuesToDataChangedNotificationEventElement(final Document doc,
+            final Element dataChangedNotificationEventElement,
+            final DataChangeEvent<InstanceIdentifier, CompositeNode> 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<InstanceIdentifier> data, Element element, Store store,
-            Operation operation) {
+    private void addValuesFromDataToElement(final Document doc,
+            final Set<InstanceIdentifier> 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<InstanceIdentifier, CompositeNode> data, Element element,
-            Store store, Operation operation) {
+    private void addValuesFromDataToElement(final Document doc,
+            final Map<InstanceIdentifier, CompositeNode> 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<String, String> 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<String, String> prefixes) {
+    private static void writeIdentifierWithNamespacePrefix(final Element element,
+            final StringBuilder textContent, final QName qName, final Map<String, String> 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 <a-z>.
      */
-    private static String generateNewPrefix(Collection<String> prefixes) {
+    private static String generateNewPrefix(final Collection<String> prefixes) {
         StringBuilder result = null;
         Random random = new Random();
         do {
@@ -571,7 +574,7 @@ public class ListenerAdapter implements DataChangeListener {
      *            ListenerRegistration<DataChangeListener>
      */
     public void setRegistration(
-            ListenerRegistration<DataChangeListener> registration) {
+            final ListenerRegistration<DataChangeListener> 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;
         }
     }
index b5d6a6ea9be647d22c1dc8a75609506433e850f6..26e4936d3f27d0d20e3875fe051335d79beae3be 100644 (file)
@@ -46,7 +46,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     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<Object>
      * @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<Object>
                 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<Object>
      * @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<Object>
      * @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<Object>
     }
 
     @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<Object>
      *            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();
     }
 
index 07d781028b99feaa03cd8dc610f499f63a0ca1dc..3f2c212bd87785ccbf021749d9bddb1db069bf6f 100644 (file)
@@ -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);
     }
 
 }
index f0a232fba670539c5a872e5894a89bd7c214c778..41a1c3827d21973180e01b7fd3cb11e2e73f993c 100644 (file)
@@ -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("<module");
         assertEquals("<module element is returned more then once", 2, split.length);
 
     }
 
-    private void validateModulesResponseXml(Response response) {
+    private void validateModulesResponseXml(final Response response) {
         assertEquals(200, response.getStatus());
         String responseBody = response.readEntity(String.class);
 
@@ -506,7 +506,7 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private void validateModulesResponseJson(Response response) {
+    private void validateModulesResponseJson(final Response response) {
         assertEquals(200, response.getStatus());
         String responseBody = response.readEntity(String.class);
 
@@ -518,7 +518,7 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private Matcher prepareJsonRegex(String module, String revision, String namespace, String searchIn) {
+    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace, final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -544,7 +544,7 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher prepareXmlRegex(String module, String revision, String namespace, String searchIn) {
+    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace, final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -572,13 +572,13 @@ public class RestGetOperationTest extends JerseyTest {
         return ptrn.matcher(searchIn);
     }
 
-    private void prepareMockForModulesTest(ControllerContext mockedControllerContext) throws FileNotFoundException {
+    private void prepareMockForModulesTest(final ControllerContext mockedControllerContext) throws FileNotFoundException {
         SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
         mockedControllerContext.setGlobalSchema(schemaContext);
         // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
     }
 
-    private int get(String uri, String mediaType) {
+    private int get(final String uri, final String mediaType) {
         return target(uri).request(mediaType).get().getStatus();
     }
 
@@ -621,179 +621,179 @@ public class RestGetOperationTest extends JerseyTest {
         ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
 
         CompositeNode depth1Cont = toCompositeNode(
-            toCompositeNodeData( toNestedQName( "depth1-cont" ),
-                toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                    toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                        toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                            toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                        ),
-                        toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-                ),
-                toCompositeNodeData( toNestedQName( "depth2-cont2" ),
-                    toCompositeNodeData( toNestedQName( "depth3-cont2" ),
-                        toCompositeNodeData( toNestedQName( "depth4-cont2" ),
-                            toSimpleNodeData( toNestedQName( "depth5-leaf2" ), "depth5-leaf2-value" )
-                        ),
-                        toSimpleNodeData( toNestedQName( "depth4-leaf2" ), "depth4-leaf2-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth3-leaf2" ), "depth3-leaf2-value" )
-                ),
-                toSimpleNodeData( toNestedQName( "depth2-leaf1" ), "depth2-leaf1-value" )
-            ) );
+                toCompositeNodeData( toNestedQName( "depth1-cont" ),
+                        toCompositeNodeData( toNestedQName( "depth2-cont1" ),
+                                toCompositeNodeData( toNestedQName( "depth3-cont1" ),
+                                        toCompositeNodeData( toNestedQName( "depth4-cont1" ),
+                                                toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
+                                                ),
+                                                toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
+                                        ),
+                                        toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
+                                ),
+                                toCompositeNodeData( toNestedQName( "depth2-cont2" ),
+                                        toCompositeNodeData( toNestedQName( "depth3-cont2" ),
+                                                toCompositeNodeData( toNestedQName( "depth4-cont2" ),
+                                                        toSimpleNodeData( toNestedQName( "depth5-leaf2" ), "depth5-leaf2-value" )
+                                                        ),
+                                                        toSimpleNodeData( toNestedQName( "depth4-leaf2" ), "depth4-leaf2-value" )
+                                                ),
+                                                toSimpleNodeData( toNestedQName( "depth3-leaf2" ), "depth3-leaf2-value" )
+                                        ),
+                                        toSimpleNodeData( toNestedQName( "depth2-leaf1" ), "depth2-leaf1-value" )
+                        ) );
 
         when( brokerFacade.readConfigurationData( any( InstanceIdentifier.class ) ) )
-            .thenReturn( depth1Cont );
+        .thenReturn( depth1Cont );
 
         // Test config with depth 1
 
         Response response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "1" )
-                                .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
         verifyXMLResponse( response, expectEmptyContainer( "depth1-cont" ) );
 
         // Test config with depth 2
 
         response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "2" )
-                       .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
-//        String xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
-//        Response mr=mock(Response.class);
-//        when(mr.getEntity()).thenReturn( new java.io.StringBufferInputStream(xml) );
+        //        String xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
+        //        Response mr=mock(Response.class);
+        //        when(mr.getEntity()).thenReturn( new java.io.StringBufferInputStream(xml) );
 
         verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectEmptyContainer( "depth2-cont1" ),
-                expectEmptyContainer( "depth2-cont2" ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+                expectContainer( "depth1-cont",
+                        expectEmptyContainer( "depth2-cont1" ),
+                        expectEmptyContainer( "depth2-cont2" ),
+                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
+                        ) );
 
         // Test config with depth 3
 
         response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "3" )
-                       .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
         verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectEmptyContainer( "depth3-cont1" ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectEmptyContainer( "depth3-cont2" ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-           ) );
+                expectContainer( "depth1-cont",
+                        expectContainer( "depth2-cont1",
+                                expectEmptyContainer( "depth3-cont1" ),
+                                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
+                                ),
+                                expectContainer( "depth2-cont2",
+                                        expectEmptyContainer( "depth3-cont2" ),
+                                        expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
+                                        ),
+                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
+                        ) );
 
         // Test config with depth 4
 
         response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "4" )
-                      .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
         verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectEmptyContainer( "depth4-cont1" ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectEmptyContainer( "depth4-cont2" ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+                expectContainer( "depth1-cont",
+                        expectContainer( "depth2-cont1",
+                                expectContainer( "depth3-cont1",
+                                        expectEmptyContainer( "depth4-cont1" ),
+                                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
+                                        ),
+                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
+                                ),
+                                expectContainer( "depth2-cont2",
+                                        expectContainer( "depth3-cont2",
+                                                expectEmptyContainer( "depth4-cont2" ),
+                                                expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
+                                                ),
+                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
+                                        ),
+                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
+                        ) );
 
         // Test config with depth 5
 
         response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "5" )
-                       .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
         verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectContainer( "depth4-cont1",
-                            expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                        ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectContainer( "depth4-cont2",
-                            expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                        ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+                expectContainer( "depth1-cont",
+                        expectContainer( "depth2-cont1",
+                                expectContainer( "depth3-cont1",
+                                        expectContainer( "depth4-cont1",
+                                                expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
+                                                ),
+                                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
+                                        ),
+                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
+                                ),
+                                expectContainer( "depth2-cont2",
+                                        expectContainer( "depth3-cont2",
+                                                expectContainer( "depth4-cont2",
+                                                        expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
+                                                        ),
+                                                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
+                                                ),
+                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
+                                        ),
+                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
+                        ) );
 
         // Test config with depth unbounded
 
         response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "unbounded" )
-                       .request( "application/xml" ).get();
+                .request( "application/xml" ).get();
 
         verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectContainer( "depth4-cont1",
-                            expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                        ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectContainer( "depth4-cont2",
-                            expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                        ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+                expectContainer( "depth1-cont",
+                        expectContainer( "depth2-cont1",
+                                expectContainer( "depth3-cont1",
+                                        expectContainer( "depth4-cont1",
+                                                expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
+                                                ),
+                                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
+                                        ),
+                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
+                                ),
+                                expectContainer( "depth2-cont2",
+                                        expectContainer( "depth3-cont2",
+                                                expectContainer( "depth4-cont2",
+                                                        expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
+                                                        ),
+                                                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
+                                                ),
+                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
+                                        ),
+                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
+                        ) );
 
         // Test operational
 
         CompositeNode depth2Cont1 = toCompositeNode(
-            toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                    toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                        toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                ),
-                toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-            ) );
+                toCompositeNodeData( toNestedQName( "depth2-cont1" ),
+                        toCompositeNodeData( toNestedQName( "depth3-cont1" ),
+                                toCompositeNodeData( toNestedQName( "depth4-cont1" ),
+                                        toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
+                                        ),
+                                        toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
+                                ),
+                                toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
+                        ) );
 
         when( brokerFacade.readOperationalData( any( InstanceIdentifier.class ) ) )
-             .thenReturn( depth2Cont1 );
+        .thenReturn( depth2Cont1 );
 
         response = target( "/operational/nested-module:depth1-cont/depth2-cont1" )
-                       .queryParam( "depth", "3" ).request( "application/xml" ).get();
+                .queryParam( "depth", "3" ).request( "application/xml" ).get();
 
         verifyXMLResponse( response,
-            expectContainer( "depth2-cont1",
-                expectContainer( "depth3-cont1",
-                    expectEmptyContainer( "depth4-cont1" ),
-                    expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                ),
-                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-            ) );
+                expectContainer( "depth2-cont1",
+                        expectContainer( "depth3-cont1",
+                                expectEmptyContainer( "depth4-cont1" ),
+                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
+                                ),
+                                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
+                        ) );
     }
 
     @Test
@@ -805,12 +805,12 @@ public class RestGetOperationTest extends JerseyTest {
         paramMap.putSingle( "depth", "1o" );
         UriInfo mockInfo = mock( UriInfo.class );
         when( mockInfo.getQueryParameters( false ) ).thenAnswer(
-            new Answer<MultivaluedMap<String,String>>() {
-                @Override
-                public MultivaluedMap<String, String> answer( InvocationOnMock invocation ) {
-                    return paramMap;
-                }
-            } );
+                new Answer<MultivaluedMap<String,String>>() {
+                    @Override
+                    public MultivaluedMap<String, String> 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<ImmutableCompositeNode> 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 );
     }
 }
index 33d4b325bef2c6abc6424c044e8a572acb619ac2..efdb7b240c94a9fb9b47aec81d71ff99e61ebff5 100644 (file)
@@ -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<Module> 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);
     }
 }
index 0e929afc8461c5da04bafa6dc44e7c782f83417d..755ca7501582e43651d51046de5a057d5adbe038 100644 (file)
@@ -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<DataSchemaNode> 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<TypeDefinition<?>> 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 );
     }
 
     /**
index b996bf12348ccc89088b1426c269049a9cf98928..fcabb088f4decbac32df1ba08648cb3d2d18fdf9 100644 (file)
@@ -46,7 +46,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
     private final Map<InstanceIdentifier, Long> instanceIdToLongId = new TreeMap<>(
             new Comparator<InstanceIdentifier>() {
                 @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<PathArgument> 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<QName, Object> 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<Api> 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);
index 2816f79e2413a90afc4125346a1a64804658a548..05a76a4cb7ca0551d0bb55322b4603f78eb7fd4b 100644 (file)
@@ -24,7 +24,6 @@
 <script src='swagger-ui.js' type='text/javascript'></script>\r
 <script src='lib/odl/list_mounts.js' type='text/javascript'></script>\r
 <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>\r
-<script src='lib/odl/rest-tree.js' type='text/javascript'></script>\r
 <script src='lib/odl/swagger.js' type='text/javascript'></script>\r
 \r
 <script type="text/javascript">\r
index 8390a385e6a136a29d79e64376a0fadf8fa03757..07c9378439d2f66551672d8a08ec20785a0a074b 100644 (file)
@@ -2,6 +2,7 @@ package org.opendaylight.controller.sal.rest.doc.impl;
 
 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 java.io.File;
@@ -65,6 +66,24 @@ public class ApiDocGeneratorTest {
         }
     }
 
+    @Test
+    public void testEdgeCases() throws Exception {
+        Preconditions.checkArgument(helper.getModules() != null, "No modules found");
+
+        for (Entry<File, Module> m : helper.getModules().entrySet()) {
+            if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) {
+                ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(),
+                        "http://localhost:8080/restconf", "");
+                Assert.assertNotNull(doc);
+
+                //testing bugs.opendaylight.org bug 1290. UnionType model type.
+                String jsonString = doc.getModels().toString();
+                assertTrue(
+                        jsonString.contains( "testUnion\":{\"type\":\"integer or string\",\"required\":false}" ) );
+            }
+        }
+    }
+
     private void validateToaster(ApiDeclaration doc) throws Exception {
         Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[] {
                 "/config/toaster2:toaster/", "/operational/toaster2:toaster/",
@@ -99,6 +118,7 @@ public class ApiDocGeneratorTest {
             expectedConfigMethods.removeAll(actualConfigMethods);
             fail("Missing expected method on config API: " + expectedConfigMethods);
         }
+
         // TODO: we should really do some more validation of the
         // documentation...
         /**
index 782998067f80d5fc35a1249dedbaa8e0dcf4e37b..827708f31ceb52fbc39bd8c202fa630cf698d225 100644 (file)
@@ -9,6 +9,13 @@
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
 import com.google.common.collect.Maps;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
@@ -21,18 +28,12 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
 public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     private static final Logger logger = LoggerFactory.getLogger(YangStoreSnapshotImpl.class);
 
 
     private final Map<String /* Namespace from yang file */,
-            Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
+    Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
 
 
     private final Map<QName, Map<String, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries;
@@ -40,7 +41,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     private final SchemaContext schemaContext;
 
 
-    public YangStoreSnapshotImpl(SchemaContext resolveSchemaContext) {
+    public YangStoreSnapshotImpl(final SchemaContext resolveSchemaContext) {
         logger.trace("Resolved modules:{}", resolveSchemaContext.getModules());
         this.schemaContext = resolveSchemaContext;
         // JMX generator
@@ -60,7 +61,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
                     qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
                 } else {
                     throw new IllegalStateException("Cannot add two SIE with same qname "
-                                    + sieEntry.getValue());
+                            + sieEntry.getValue());
                 }
             }
         }
@@ -75,7 +76,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
             TypeProviderWrapper typeProviderWrapper = new TypeProviderWrapper(
                     new TypeProviderImpl(resolveSchemaContext));
 
-            QName qName = new QName(module.getNamespace(), module.getRevision(), module.getName());
+            QName qName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
 
             Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs =
                     Collections.unmodifiableMap(ModuleMXBeanEntry.create(module, qNamesToSIEs, resolveSchemaContext,
@@ -105,7 +106,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     }
 
     @Override
-    public String getModuleSource(org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
+    public String getModuleSource(final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
         return schemaContext.getModuleSource(moduleIdentifier).get();
     }
 
index a063f5786a8f4796d95023849fbc6243e873fa01..1e650c08b124a460c7d19f65200c1b0868ccee17 100644 (file)
@@ -8,14 +8,12 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.matchers.JUnitMatchers;
-import org.opendaylight.controller.config.api.LookupRegistry;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.yangtools.yang.common.QName;
 
 import java.net.URI;
 import java.text.ParseException;
@@ -24,9 +22,12 @@ import java.util.Date;
 import java.util.Map;
 import java.util.Set;
 
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.matchers.JUnitMatchers;
+import org.opendaylight.controller.config.api.LookupRegistry;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.yangtools.yang.common.QName;
 
 public class NetconfOperationServiceImplTest {
 
@@ -72,15 +73,15 @@ public class NetconfOperationServiceImplTest {
             Assert.assertThat(
                     message,
                     JUnitMatchers
-                            .containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]"));
+                    .containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]"));
             Assert.assertThat(
                     message,
                     JUnitMatchers
-                            .containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]"));
+                    .containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]"));
         }
     }
 
-    private YangStoreSnapshot mockYangStoreSnapshot(String... qnames) {
+    private YangStoreSnapshot mockYangStoreSnapshot(final String... qnames) {
         YangStoreSnapshot mock = mock(YangStoreSnapshot.class);
 
         Map<String, Map<String, ModuleMXBeanEntry>> map = Maps.newHashMap();
@@ -99,18 +100,18 @@ public class NetconfOperationServiceImplTest {
         return mock;
     }
 
-    private ModuleMXBeanEntry mockMBeanEntry(String qname) {
+    private ModuleMXBeanEntry mockMBeanEntry(final String qname) {
         ModuleMXBeanEntry mock = mock(ModuleMXBeanEntry.class);
         QName q = getQName(qname);
         doReturn(q).when(mock).getYangModuleQName();
         return mock;
     }
 
-    private QName getQName(String qname) {
-        return new QName(URI.create("namespace"), date1970_01_01, qname);
+    private QName getQName(final String qname) {
+        return QName.create(URI.create("namespace"), date1970_01_01, qname);
     }
 
-    private LookupRegistry mockJmxClient(String... visibleQNames) {
+    private LookupRegistry mockJmxClient(final String... visibleQNames) {
         LookupRegistry mock = mock(LookupRegistry.class);
         Set<String> qnames = Sets.newHashSet();
         for (String visibleQName : visibleQNames) {
index f0e1b3f51fd1abdb445bc33f221f1e90aff1a6dc..c770bde9206c03bba89027bc77b5fcb835e8dd03 100644 (file)
@@ -236,7 +236,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
         @Override
         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-            logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
+            logger.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
             cancelTimeout();
             negotiationFailed(cause);
             changeState(State.FAILED);
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java
new file mode 100644 (file)
index 0000000..bebac37
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron;
+
+/**
+ * This class contains behaviour common to Neutron configuration objects
+ */
+public interface INeutronObject {
+    public String getID();
+    public void setID(String id);
+}
index 5b35dc2b34ff73519e4350fa7070ec06cf60801d..a3c38a9265dc50c814a83c776a0c0c7e599f1dba 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement(name = "network")
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronNetwork extends ConfigurationObject implements Serializable {
+public class NeutronNetwork extends ConfigurationObject implements Serializable, INeutronObject {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -93,6 +93,8 @@ public class NeutronNetwork extends ConfigurationObject implements Serializable
 
     public String getID() { return networkUUID; }
 
+    public void setID(String id) { this.networkUUID = id; }
+
     public String getNetworkUUID() {
         return networkUUID;
     }
index 680a07453b94b3f56072804b2981006574837f5a..b32b01cb3f3015930510d22fd1a39836a25a0cbb 100644 (file)
@@ -25,7 +25,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronPort extends ConfigurationObject implements Serializable {
+public class NeutronPort extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -76,6 +76,8 @@ public class NeutronPort extends ConfigurationObject implements Serializable {
 
     public String getID() { return portUUID; }
 
+    public void setID(String id) { this.portUUID = id; }
+
     public String getPortUUID() {
         return portUUID;
     }
index fa35f71fd6ae425aac90f7d31524198413ade2f2..2c10cca0c0e4d0819f91d2f7d5543897d216cd65 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronRouter extends ConfigurationObject implements Serializable {
+public class NeutronRouter extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -57,6 +57,8 @@ public class NeutronRouter extends ConfigurationObject implements Serializable {
 
     public String getID() { return routerUUID; }
 
+    public void setID(String id) { this.routerUUID = id; }
+
     public String getRouterUUID() {
         return routerUUID;
     }
index ae84a72bbac84ddda56c102972c894e21873a603..840029006be5b16a4d394bae0d6daa0b5efd65a5 100644 (file)
@@ -25,7 +25,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronSubnet extends ConfigurationObject implements Serializable {
+public class NeutronSubnet extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -83,6 +83,8 @@ public class NeutronSubnet extends ConfigurationObject implements Serializable {
 
     public String getID() { return subnetUUID; }
 
+    public void setID(String id) { this.subnetUUID = id; }
+
     public String getSubnetUUID() {
         return subnetUUID;
     }
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java
new file mode 100644 (file)
index 0000000..8e0ff5c
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronObject;
+
+import java.util.List;
+
+public interface INeutronRequest<T extends INeutronObject> {
+    public T getSingleton();
+    public boolean isSingleton();
+    public List<T> getBulk();
+}
index cebd3c267dd1a1ad2d3b345f2f97d498046631b0..a4c113c2c1803081409e61c4132770482d51f3c0 100644 (file)
@@ -19,7 +19,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
 
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
-public class NeutronNetworkRequest {
+public class NeutronNetworkRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -29,9 +29,18 @@ public class NeutronNetworkRequest {
     @XmlElement(name="networks")
     List<NeutronNetwork> bulkRequest;
 
+    @XmlElement(name="networks_links")
+    List<NeutronPageLink> links;
+
     NeutronNetworkRequest() {
     }
 
+    NeutronNetworkRequest(List<NeutronNetwork> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonNetwork = null;
+    }
+
     NeutronNetworkRequest(List<NeutronNetwork> bulk) {
         bulkRequest = bulk;
         singletonNetwork = null;
index 52c3337e40047fb844352fd9dcc0b6c596fcb8d0..9de5aef5f421eb2436ac73a6dff63e24efcf4c64 100644 (file)
@@ -9,8 +9,6 @@
 package org.opendaylight.controller.networkconfig.neutron.northbound;
 
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -33,6 +31,7 @@ import javax.ws.rs.core.Response;
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
 import org.codehaus.enunciate.jaxrs.TypeHint;
+
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkAware;
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
@@ -95,13 +94,13 @@ public class NeutronNetworksNorthbound {
             @QueryParam("provider_network_type") String queryProviderNetworkType,
             @QueryParam("provider_physical_network") String queryProviderPhysicalNetwork,
             @QueryParam("provider_segmentation_id") String queryProviderSegmentationID,
-            // pagination
+            // linkTitle
             @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
-        INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
+        INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
         if (networkInterface == null) {
             throw new ServiceUnavailableException("Network CRUD Interface "
                     + RestMessages.SERVICEUNAVAILABLE.toString());
@@ -139,89 +138,11 @@ public class NeutronNetworksNorthbound {
             }
         }
 
-        Comparator<NeutronNetwork> neutronNetworkComparator = new Comparator<NeutronNetwork>() {
-            @Override
-            public int compare(NeutronNetwork o1, NeutronNetwork o2) {
-                return o1.getID().compareTo(o2.getID());
-            }
-        };
-
-        Collections.sort(ans, neutronNetworkComparator);
-
         if (limit != null && ans.size() > 1) {
-            List<NeutronPageLink> links = new ArrayList<>();
-            Integer startPos = null;
-            String startMarker;
-            String endMarker;
-            Boolean firstPage = false;
-            Boolean lastPage = false;
-
-            if (marker == null) {
-                startPos = 0;
-            }
-
-            else {
-
-                NeutronNetwork markerNetwork = new NeutronNetwork();
-                markerNetwork.setNetworkUUID(marker);
-
-                startPos = Collections.binarySearch(ans, markerNetwork, neutronNetworkComparator);
-
-                if (!pageReverse){
-                    startPos = startPos + 1;
-                }
-                else {
-                    startPos = startPos - limit;
-                }
-
-            }
-
-            if (startPos == null) {
-                throw new ResourceNotFoundException("UUID for marker:" + marker + " could not be found");
-            }
-
-            if (startPos == 0){
-                firstPage = true;
-            }
-
-            if (startPos + limit >= ans.size()) {
-                ans = ans.subList(startPos, ans.size());
-                startMarker = ans.get(0).getID();
-                endMarker = ans.get(ans.size() - 1).getID();
-                lastPage = true;
-            }
-            else if (startPos < 0) {
-                if (startPos + limit > 0) {
-                    ans = ans.subList(0, startPos + limit);
-                    startMarker = ans.get(0).getID();
-                    endMarker = ans.get(ans.size() - 1).getID();
-                    firstPage = true;
-                }
-                else {
-                    throw new BadRequestException("Requested page is out of bounds. Please check the supplied limit and marker");
-                }
-            }
-            else {
-                ans = ans.subList(startPos, startPos + limit);
-                startMarker = ans.get(0).getID();
-                endMarker = ans.get(limit-1).getID();
-            }
-
-            if (!lastPage) {
-                NeutronPageLink next = new NeutronPageLink();
-                next.setRef("next");
-                next.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + endMarker);
-                links.add(next);
-            }
-
-            if (!firstPage) {
-                NeutronPageLink previous = new NeutronPageLink();
-                previous.setRef("previous");
-                previous.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + startMarker + "&page_reverse=True");
-                links.add(previous);
-            }
-
-            return Response.status(200).entity(new PaginatedNeutronNetworkRequest(ans, links)).build();
+            // Return a paginated request
+            NeutronNetworkRequest request = (NeutronNetworkRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronNetwork.class);
+            return Response.status(200).entity(request).build();
         }
 
     return Response.status(200).entity(new NeutronNetworkRequest(ans)).build();
index 9b3399d9a8bfe72266843b0d4d8c34d6b163ef52..12b58aa2abc54e30799fd0458a4e126b9185124a 100644 (file)
@@ -19,7 +19,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
 
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
-public class NeutronPortRequest {
+public class NeutronPortRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -29,9 +29,18 @@ public class NeutronPortRequest {
     @XmlElement(name="ports")
     List<NeutronPort> bulkRequest;
 
+    @XmlElement(name="ports_links")
+    List<NeutronPageLink> links;
+
     NeutronPortRequest() {
     }
 
+    public NeutronPortRequest(List<NeutronPort> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonPort = null;
+    }
+
     NeutronPortRequest(List<NeutronPort> bulk) {
         bulkRequest = bulk;
         singletonPort = null;
index 1a2512fde3c3fd6c689a872f9ee148bba4a67521..5451fbf3e129e4be88addabcc7816e308c2cb2b7 100644 (file)
@@ -15,6 +15,7 @@ import java.util.List;
 
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
@@ -22,8 +23,10 @@ import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -69,6 +72,9 @@ public class NeutronPortsNorthbound {
         return o.extractFields(fields);
     }
 
+    @Context
+    UriInfo uriInfo;
+
     /**
      * Returns a list of all Ports */
 
@@ -92,10 +98,10 @@ public class NeutronPortsNorthbound {
             @QueryParam("device_id") String queryDeviceID,
             @QueryParam("device_owner") String queryDeviceOwner,
             @QueryParam("tenant_id") String queryTenantID,
-            // pagination
-            @QueryParam("limit") String limit,
+            // linkTitle
+            @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
-            @QueryParam("page_reverse") String pageReverse
+            @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
@@ -124,7 +130,14 @@ public class NeutronPortsNorthbound {
                 }
             }
         }
-        //TODO: apply pagination to results
+
+        if (limit != null && ans.size() > 1) {
+            // Return a paginated request
+            NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronPort.class);
+            return Response.status(200).entity(request).build();
+        }
+
         return Response.status(200).entity(
                 new NeutronPortRequest(ans)).build();
     }
index aed9db58bd34c3255c54830c8b76957da6d4de5c..57a724c1cc60936b3a15ed80ba0c1b9bc6d53288 100644 (file)
@@ -20,7 +20,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronSubnetRequest {
+public class NeutronSubnetRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -30,16 +30,28 @@ public class NeutronSubnetRequest {
     @XmlElement(name="subnets")
     List<NeutronSubnet> bulkRequest;
 
+    @XmlElement(name="subnets_links")
+    List<NeutronPageLink> links;
+
     NeutronSubnetRequest() {
     }
 
+    public NeutronSubnetRequest(List<NeutronSubnet> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonSubnet = null;
+    }
+
     NeutronSubnetRequest(List<NeutronSubnet> bulk) {
         bulkRequest = bulk;
         singletonSubnet = null;
+        links = null;
     }
 
     NeutronSubnetRequest(NeutronSubnet subnet) {
         singletonSubnet = subnet;
+        bulkRequest = null;
+        links = null;
     }
 
     public NeutronSubnet getSingleton() {
index f397eb3a97b0630002b3fc1b70901a1a25cf0609..8f20269603b1ed1802fc04812974125016c1811b 100644 (file)
@@ -13,8 +13,10 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
@@ -22,8 +24,10 @@ import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -65,6 +69,8 @@ public class NeutronSubnetsNorthbound {
         return o.extractFields(fields);
     }
 
+    @Context
+    UriInfo uriInfo;
 
     /**
      * Returns a list of all Subnets */
@@ -89,13 +95,13 @@ public class NeutronSubnetsNorthbound {
             @QueryParam("tenant_id") String queryTenantID,
             @QueryParam("ipv6_address_mode") String queryIpV6AddressMode,
             @QueryParam("ipv6_ra_mode") String queryIpV6RaMode,
-            // pagination
-            @QueryParam("limit") String limit,
+            // linkTitle
+            @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
-            @QueryParam("page_reverse") String pageReverse
+            @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
-        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
+        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
         if (subnetInterface == null) {
             throw new ServiceUnavailableException("Subnet CRUD Interface "
                     + RestMessages.SERVICEUNAVAILABLE.toString());
@@ -122,7 +128,14 @@ public class NeutronSubnetsNorthbound {
                 }
             }
         }
-        //TODO: apply pagination to results
+
+        if (limit != null && ans.size() > 1) {
+            // Return a paginated request
+            NeutronSubnetRequest request = (NeutronSubnetRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronSubnet.class);
+            return Response.status(200).entity(request).build();
+        }
+
         return Response.status(200).entity(
                 new NeutronSubnetRequest(ans)).build();
     }
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java
deleted file mode 100644 (file)
index c050661..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2014 Hewlett-Packard Development Company L.P
- *
- * 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
- *
- * Authors : Dave Tucker
- */
-
-package org.opendaylight.controller.networkconfig.neutron.northbound;
-
-import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.util.List;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.NONE)
-
-public class PaginatedNeutronNetworkRequest {
-
-    @XmlElement (name="networks")
-    List<NeutronNetwork> networks;
-
-    @XmlElement (name="network_links")
-    List<NeutronPageLink> networkLinks;
-
-    public PaginatedNeutronNetworkRequest() {
-    }
-
-    public PaginatedNeutronNetworkRequest(List<NeutronNetwork> networks, List<NeutronPageLink> networkLinks) {
-        this.networks = networks;
-        this.networkLinks = networkLinks;
-    }
-
-    public List<NeutronNetwork> getNetworks() {
-        return networks;
-    }
-
-    public void setNetworks(List<NeutronNetwork> networks) {
-        this.networks = networks;
-    }
-
-    public List<NeutronPageLink> getNetworkLinks() {
-        return networkLinks;
-    }
-
-    public void setNetworkLinks(List<NeutronPageLink> networkLinks) {
-        this.networkLinks = networkLinks;
-    }
-}
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java
new file mode 100644 (file)
index 0000000..8f05e76
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronObject;
+import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
+import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
+import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+
+import javax.ws.rs.core.UriInfo;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class PaginatedRequestFactory {
+
+    public static class PaginationResults<T extends INeutronObject> {
+        List<T> collection;
+        List<NeutronPageLink> links;
+
+        public PaginationResults(List<T> collection, List<NeutronPageLink> links) {
+            this.collection = collection;
+            this.links = links;
+        }
+    }
+
+    public static <T extends INeutronObject> INeutronRequest createRequest(Integer limit, String marker,
+                                                                           Boolean pageReverse,
+                                                                           UriInfo uriInfo,
+                                                                           List<T> collection,
+                                                                           Class<T> clazz) {
+        PaginationResults results = _paginate(limit, marker, pageReverse, uriInfo, collection);
+
+        if (clazz.equals(NeutronNetwork.class)){
+            return new NeutronNetworkRequest(results.collection, results.links);
+        }
+        if (clazz.equals(NeutronSubnet.class)){
+            return new NeutronSubnetRequest(results.collection, results.links);
+        }
+        if (clazz.equals(NeutronPort.class)){
+            return new NeutronPortRequest(results.collection, results.links);
+        }
+        return null;
+    }
+
+    private static <T extends INeutronObject> PaginationResults _paginate(Integer limit, String marker, Boolean pageReverse, UriInfo uriInfo, List<T> collection) {
+        List<NeutronPageLink> links = new ArrayList<>();
+        Integer startPos = null;
+        String startMarker;
+        String endMarker;
+        Boolean firstPage = false;
+        Boolean lastPage = false;
+
+        Comparator<INeutronObject> neutronObjectComparator = new Comparator<INeutronObject>() {
+            @Override
+            public int compare(INeutronObject o1, INeutronObject o2) {
+                return o1.getID().compareTo(o2.getID());
+            }
+        };
+
+        Collections.sort(collection, neutronObjectComparator);
+
+        if (marker == null) {
+            startPos = 0;
+        }
+
+        else {
+
+            class MarkerObject implements INeutronObject {
+                private String id;
+
+                public String getID() {
+                    return id;
+                }
+
+                public void setID(String id) {
+                    this.id = id;
+                }
+            }
+
+            INeutronObject markerObject = new MarkerObject();
+
+            markerObject.setID(marker);
+
+            startPos = Collections.binarySearch(collection, markerObject, neutronObjectComparator);
+
+            if (!pageReverse){
+                startPos = startPos + 1;
+            }
+            else {
+                startPos = startPos - limit;
+            }
+
+        }
+
+        if (startPos == null) {
+            throw new ResourceNotFoundException("UUID for marker:" + marker + " could not be found");
+        }
+
+        if (startPos == 0){
+            firstPage = true;
+        }
+
+        if (startPos + limit >= collection.size()) {
+            collection = collection.subList(startPos, collection.size());
+            startMarker = collection.get(0).getID();
+            endMarker = collection.get(collection.size() - 1).getID();
+            lastPage = true;
+        }
+        else if (startPos < 0) {
+            if (startPos + limit > 0) {
+                collection = collection.subList(0, startPos + limit);
+                startMarker = collection.get(0).getID();
+                endMarker = collection.get(collection.size() - 1).getID();
+                firstPage = true;
+            }
+            else {
+                throw new BadRequestException("Requested page is out of bounds. Please check the supplied limit and marker");
+            }
+        }
+        else {
+            collection = collection.subList(startPos, startPos + limit);
+            startMarker = collection.get(0).getID();
+            endMarker = collection.get(limit-1).getID();
+        }
+
+        if (!lastPage) {
+            NeutronPageLink next = new NeutronPageLink();
+            next.setRef("next");
+            next.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + endMarker);
+            links.add(next);
+        }
+
+        if (!firstPage) {
+            NeutronPageLink previous = new NeutronPageLink();
+            previous.setRef("previous");
+            previous.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + startMarker + "&page_reverse=True");
+            links.add(previous);
+        }
+
+        return new PaginationResults(collection, links);
+    }
+}