Merge "bug 537 - Node Reconciliation"
authorEd Warnicke <eaw@cisco.com>
Fri, 15 Aug 2014 19:54:29 +0000 (19:54 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 15 Aug 2014 19:54:29 +0000 (19:54 +0000)
63 files changed:
opendaylight/md-sal/sal-binding-broker/pom.xml
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/DataBrokerImplModule.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java [moved from opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/ClusterWrapper.java with 57% similarity]
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/RuntimeMappingModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.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/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/SingletonHolder.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootDataBrokerImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/forward/DomForwardedDataBrokerImpl.java [new file with mode: 0644]
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/md/sal/binding/impl/test/BindingNormalizedCodecTest.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/DataBrokerTestCustomizer.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/MultipleAugmentationPutsTest.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java
opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java
opendaylight/md-sal/sal-binding-it/src/test/java/org/opendaylight/controller/test/sal/binding/it/DataServiceTest.java
opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml
opendaylight/md-sal/sal-remoterpc-connector/pom.xml
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcImplementation.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RoutedRpcListener.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcBroker.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcListener.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRoutedRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpcReply.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpcReply.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRoutedRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRpc.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRoutedRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRpc.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RoutingTableData.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/ClusterWrapperImpl.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOld.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOld.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/ActorUtil.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogic.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/RoutingLogic.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/main/resources/application.conf
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/ActorSystemFactoryTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RemoteRpcProviderTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RouteRpcListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RpcBrokerTest.java
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RpcListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOldTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOldTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketStoreTest.java
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/GossiperTest.java
opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/test/resources/application.conf
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java
opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/NodeConnectorStatsTracker.java
opendaylight/md-sal/topology-manager/src/main/java/org/opendaylight/md/controller/topology/manager/FlowCapableTopologyProvider.java

index 539f9d45c8b8c30ebfcde9da22229bd4c2a547ab..74cceb1cbd55fc786b78e3f111b2a82a60bd8751 100644 (file)
       <groupId>org.opendaylight.yangtools</groupId>
       <artifactId>binding-generator-impl</artifactId>
     </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>binding-data-codec</artifactId>
-      <version>0.6.2-SNAPSHOT</version>
-    </dependency>
     <dependency>
       <groupId>org.opendaylight.yangtools</groupId>
       <artifactId>yang-data-impl</artifactId>
index 93d99c832fcc2bbffe5a7c5f851fe2fec2ef7558..018e26878c9873490d6c3ed88822edb78efe0280 100644 (file)
@@ -2,13 +2,14 @@ package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
 import java.util.Collection;
 import java.util.Collections;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.sal.core.api.Broker;
 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;
 
 public class BindingAsyncDataBrokerImplModule extends
         org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModule implements
@@ -35,7 +36,7 @@ public class BindingAsyncDataBrokerImplModule extends
     @Override
     public java.lang.AutoCloseable createInstance() {
         Broker domBroker = getDomAsyncBrokerDependency();
-        BindingToNormalizedNodeCodec mappingService = getBindingMappingServiceDependency();
+        BindingIndependentMappingService mappingService = getBindingMappingServiceDependency();
 
         // FIXME: Switch this to DOM Broker registration which would not require
         // BundleContext when API are updated.
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java
new file mode 100644 (file)
index 0000000..4a4e800
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * 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
+ */
+package org.opendaylight.controller.config.yang.md.sal.binding.impl;
+
+import java.util.concurrent.ExecutorService;
+
+import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
+import org.opendaylight.controller.sal.binding.impl.RootDataBrokerImpl;
+import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingDomConnectorDeployer;
+import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndependentConnector;
+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;
+
+/**
+*
+*/
+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;
+    }
+
+}
@@ -5,16 +5,13 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
+package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-package org.opendaylight.controller.remote.rpc.registry;
 
+/**
+*
+*/
+public class DataBrokerImplModuleFactory extends
+        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModuleFactory {
 
-import akka.actor.Address;
-import akka.cluster.ClusterEvent;
-
-public interface ClusterWrapper {
-
-  ClusterEvent.CurrentClusterState getState();
-
-  Address getAddress();
 }
index 2bc673adfff4219a9b6b84b07fc478fd8fd7164b..0ea30f7e66a817f63c63cc81e20f3890170ea7b5 100644 (file)
@@ -7,10 +7,9 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import com.google.common.util.concurrent.ListeningExecutorService;
 import java.util.Collection;
 import java.util.Collections;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
@@ -19,6 +18,9 @@ import org.opendaylight.controller.sal.core.api.Broker;
 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 com.google.common.util.concurrent.ListeningExecutorService;
 
 /**
 *
@@ -49,7 +51,7 @@ public final class ForwardedCompatibleDataBrokerImplModule extends
     @Override
     public java.lang.AutoCloseable createInstance() {
         ListeningExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor();
-        BindingToNormalizedNodeCodec mappingService = getBindingMappingServiceDependency();
+        BindingIndependentMappingService mappingService = getBindingMappingServiceDependency();
 
         Broker domBroker = getDomAsyncBrokerDependency();
         ProviderSession session = domBroker.registerProvider(this, null);
@@ -58,7 +60,7 @@ public final class ForwardedCompatibleDataBrokerImplModule extends
         ForwardedBackwardsCompatibleDataBroker dataBroker = new ForwardedBackwardsCompatibleDataBroker(domDataBroker,
                 mappingService, schemaService,listeningExecutor);
 
-        dataBroker.setConnector(BindingDomConnectorDeployer.createConnector(mappingService.getLegacy()));
+        dataBroker.setConnector(BindingDomConnectorDeployer.createConnector(getBindingMappingServiceDependency()));
         dataBroker.setDomProviderContext(session);
         return dataBroker;
     }
index a15b1d746c5f5709374387f996056f6f979e2025..b0c2d742e214046be839cca263dbc0652005aa9b 100644 (file)
@@ -7,18 +7,12 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
 import java.util.Hashtable;
 import java.util.Map.Entry;
 import java.util.Set;
-import javassist.ClassPool;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+
 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.concepts.Delegator;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
@@ -35,6 +29,9 @@ import org.osgi.framework.ServiceReference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
 /**
 *
 */
@@ -45,14 +42,14 @@ public final class RuntimeMappingModule extends
 
     private BundleContext bundleContext;
 
-    public RuntimeMappingModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+    public RuntimeMappingModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
 
-    public RuntimeMappingModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
-            final RuntimeMappingModule oldModule, final java.lang.AutoCloseable oldInstance) {
+    public RuntimeMappingModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+            RuntimeMappingModule oldModule, java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
     }
 
@@ -64,48 +61,41 @@ public final class RuntimeMappingModule extends
     }
 
     @Override
-    public boolean canReuseInstance(final AbstractRuntimeMappingModule oldModule) {
+    public boolean canReuseInstance(AbstractRuntimeMappingModule oldModule) {
         return true;
     }
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-        final GeneratedClassLoadingStrategy classLoading = getGlobalClassLoadingStrategy();
-        final BindingIndependentMappingService legacyMapping = getGlobalLegacyMappingService(classLoading);
-        BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(new StreamWriterGenerator(SingletonHolder.JAVASSIST));
-        BindingToNormalizedNodeCodec instance = new BindingToNormalizedNodeCodec(classLoading, legacyMapping, codecRegistry);
-        bundleContext.registerService(SchemaContextListener.class, instance, new Hashtable<String,String>());
-        return instance;
-    }
 
-    private BindingIndependentMappingService getGlobalLegacyMappingService(final GeneratedClassLoadingStrategy classLoading) {
-        BindingIndependentMappingService potential = tryToReuseGlobalMappingServiceInstance();
-        if(potential == null) {
-            potential =  new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(),classLoading);
-            bundleContext.registerService(SchemaContextListener.class, (SchemaContextListener) potential, new Hashtable<String,String>());
+        RuntimeGeneratedMappingServiceProxy potential = tryToReuseGlobalInstance();
+        if(potential != null) {
+            return potential;
         }
-        return potential;
-    }
 
-    private GeneratedClassLoadingStrategy getGlobalClassLoadingStrategy() {
-        ServiceReference<GeneratedClassLoadingStrategy> ref = bundleContext.getServiceReference(GeneratedClassLoadingStrategy.class);
-        return bundleContext.getService(ref);
+        final RuntimeGeneratedMappingServiceImpl service = new RuntimeGeneratedMappingServiceImpl(SingletonHolder.CLASS_POOL);
+        bundleContext.registerService(SchemaContextListener.class, service, new Hashtable<String,String>());
+        return service;
     }
 
-    private BindingIndependentMappingService tryToReuseGlobalMappingServiceInstance() {
+    private RuntimeGeneratedMappingServiceProxy tryToReuseGlobalInstance() {
         ServiceReference<BindingIndependentMappingService> serviceRef = getBundleContext().getServiceReference(BindingIndependentMappingService.class);
         if(serviceRef == null) {
             return null;
         }
-        return bundleContext.getService(serviceRef);
 
+        BindingIndependentMappingService delegate = bundleContext.getService(serviceRef);
+        if (delegate == null) {
+            return null;
+        }
+        return new RuntimeGeneratedMappingServiceProxy(getBundleContext(),serviceRef,delegate);
     }
 
     private BundleContext getBundleContext() {
         return bundleContext;
     }
 
-    public void setBundleContext(final BundleContext bundleContext) {
+    public void setBundleContext(BundleContext bundleContext) {
         this.bundleContext = bundleContext;
     }
 
@@ -118,9 +108,9 @@ public final class RuntimeMappingModule extends
         private ServiceReference<BindingIndependentMappingService> reference;
         private BundleContext bundleContext;
 
-        public RuntimeGeneratedMappingServiceProxy(final BundleContext bundleContext,
-                final ServiceReference<BindingIndependentMappingService> serviceRef,
-                final BindingIndependentMappingService delegate) {
+        public RuntimeGeneratedMappingServiceProxy(BundleContext bundleContext,
+                ServiceReference<BindingIndependentMappingService> serviceRef,
+                BindingIndependentMappingService delegate) {
             this.bundleContext = Preconditions.checkNotNull(bundleContext);
             this.reference = Preconditions.checkNotNull(serviceRef);
             this.delegate = Preconditions.checkNotNull(delegate);
@@ -132,47 +122,47 @@ public final class RuntimeMappingModule extends
         }
 
         @Override
-        public CompositeNode toDataDom(final DataObject data) {
+        public CompositeNode toDataDom(DataObject data) {
             return delegate.toDataDom(data);
         }
 
         @Override
         public Entry<YangInstanceIdentifier, CompositeNode> toDataDom(
-                final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> entry) {
+                Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> entry) {
             return delegate.toDataDom(entry);
         }
 
         @Override
         public YangInstanceIdentifier toDataDom(
-                final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
+                org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
             return delegate.toDataDom(path);
         }
 
         @Override
         public DataObject dataObjectFromDataDom(
-                final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path,
-                final CompositeNode result) throws DeserializationException {
+                org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path,
+                CompositeNode result) throws DeserializationException {
             return delegate.dataObjectFromDataDom(path, result);
         }
 
         @Override
-        public org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> fromDataDom(final YangInstanceIdentifier entry)
+        public org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> fromDataDom(YangInstanceIdentifier entry)
                 throws DeserializationException {
             return delegate.fromDataDom(entry);
         }
 
         @Override
-        public Set<QName> getRpcQNamesFor(final Class<? extends RpcService> service) {
+        public Set<QName> getRpcQNamesFor(Class<? extends RpcService> service) {
             return delegate.getRpcQNamesFor(service);
         }
 
         @Override
-        public Optional<Class<? extends RpcService>> getRpcServiceClassFor(final String namespace, final String revision) {
+        public Optional<Class<? extends RpcService>> getRpcServiceClassFor(String namespace, String revision) {
             return delegate.getRpcServiceClassFor(namespace,revision);
         }
 
         @Override
-        public DataContainer dataObjectFromDataDom(final Class<? extends DataContainer> inputClass, final CompositeNode domInput) {
+        public DataContainer dataObjectFromDataDom(Class<? extends DataContainer> inputClass, CompositeNode domInput) {
             return delegate.dataObjectFromDataDom(inputClass, domInput);
         }
 
index f843b23f9b2cc9d15a55c2d9a4373cde3baffecc..e632e6336aaf959808a28f9ecc209432c504b4eb 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.md.sal.binding.impl;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Optional;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
@@ -18,6 +19,7 @@ import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+
 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
@@ -35,28 +37,33 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBroker>, DomForwardedBroker,
-        SchemaContextListener, AutoCloseable {
+public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBroker>, DomForwardedBroker, SchemaContextListener, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(AbstractForwardedDataBroker.class);
     // The Broker to whom we do all forwarding
     private final DOMDataBroker domDataBroker;
 
+    // Mapper to convert from Binding Independent objects to Binding Aware
+    // objects
+    private final BindingIndependentMappingService mappingService;
+
     private final BindingToNormalizedNodeCodec codec;
     private BindingIndependentConnector connector;
     private ProviderSession context;
     private final ListenerRegistration<SchemaContextListener> schemaListenerRegistration;
 
-    protected AbstractForwardedDataBroker(final DOMDataBroker domDataBroker, final BindingToNormalizedNodeCodec codec,
-            final SchemaService schemaService) {
+    protected AbstractForwardedDataBroker(final DOMDataBroker domDataBroker,
+            final BindingIndependentMappingService mappingService,final SchemaService schemaService) {
         this.domDataBroker = domDataBroker;
-        this.codec = codec;
+        this.mappingService = mappingService;
+        this.codec = new BindingToNormalizedNodeCodec(mappingService);
         this.schemaListenerRegistration = schemaService.registerSchemaContextListener(this);
     }
 
@@ -64,6 +71,10 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         return codec;
     }
 
+    protected BindingIndependentMappingService getMappingService() {
+        return mappingService;
+    }
+
     @Override
     public DOMDataBroker getDelegate() {
         return domDataBroker;
@@ -71,11 +82,12 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
 
     @Override
     public void onGlobalContextUpdated(final SchemaContext ctx) {
-        // NOOP
+        codec.onGlobalContextUpdated(ctx);
     }
 
     public ListenerRegistration<DataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path, final DataChangeListener listener, final DataChangeScope triggeringScope) {
+            final InstanceIdentifier<?> path, final DataChangeListener listener,
+            final DataChangeScope triggeringScope) {
         DOMDataChangeListener domDataChangeListener = new TranslatingDataChangeInvoker(store, path, listener,
                 triggeringScope);
         YangInstanceIdentifier domPath = codec.toNormalized(path);
@@ -84,16 +96,23 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         return new ListenerRegistrationImpl(listener, domRegistration);
     }
 
-    protected Map<InstanceIdentifier<?>, DataObject> toBinding(final InstanceIdentifier<?> path,
+    protected Map<InstanceIdentifier<?>, DataObject> toBinding(
+            InstanceIdentifier<?> path,
             final Map<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized) {
         Map<InstanceIdentifier<?>, DataObject> newMap = new HashMap<>();
 
         for (Map.Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> entry : sortedEntries(normalized)) {
             try {
-                Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> potential = getCodec().toBinding(entry);
+                Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> potential = getCodec().toBinding(
+                        entry);
                 if (potential.isPresent()) {
                     Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding = potential.get();
                     newMap.put(binding.getKey(), binding.getValue());
+                } else if (entry.getKey().getLastPathArgument() instanceof YangInstanceIdentifier.AugmentationIdentifier) {
+                    DataObject bindingDataObject = getCodec().toBinding(path, entry.getValue());
+                    if (bindingDataObject != null) {
+                        newMap.put(path, bindingDataObject);
+                    }
                 }
             } catch (DeserializationException e) {
                 LOG.warn("Failed to transform {}, omitting it", entry, e);
@@ -104,7 +123,8 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
 
     private static final Comparator<Entry<YangInstanceIdentifier, ?>> MAP_ENTRY_COMPARATOR = new Comparator<Entry<YangInstanceIdentifier, ?>>() {
         @Override
-        public int compare(final Entry<YangInstanceIdentifier, ?> left, final Entry<YangInstanceIdentifier, ?> right) {
+        public int compare(final Entry<YangInstanceIdentifier, ?> left,
+                final Entry<YangInstanceIdentifier, ?> right) {
             final Iterator<?> li = left.getKey().getPathArguments().iterator();
             final Iterator<?> ri = right.getKey().getPathArguments().iterator();
 
@@ -124,7 +144,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         }
     };
 
-    private static <T> Iterable<Entry<YangInstanceIdentifier, T>> sortedEntries(final Map<YangInstanceIdentifier, T> map) {
+    private static <T> Iterable<Entry<YangInstanceIdentifier,T>> sortedEntries(final Map<YangInstanceIdentifier, T> map) {
         if (!map.isEmpty()) {
             ArrayList<Entry<YangInstanceIdentifier, T>> entries = new ArrayList<>(map.entrySet());
             Collections.sort(entries, MAP_ENTRY_COMPARATOR);
@@ -134,7 +154,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         }
     }
 
-    protected Set<InstanceIdentifier<?>> toBinding(final InstanceIdentifier<?> path,
+    protected Set<InstanceIdentifier<?>> toBinding(InstanceIdentifier<?> path,
             final Set<YangInstanceIdentifier> normalized) {
         Set<InstanceIdentifier<?>> hashSet = new HashSet<>();
         for (YangInstanceIdentifier normalizedPath : normalized) {
@@ -157,7 +177,12 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         if (path.isWildcarded()) {
             return Optional.absent();
         }
-        return (Optional) getCodec().deserializeFunction(path).apply(Optional.<NormalizedNode<?, ?>> of(data));
+
+        try {
+            return Optional.fromNullable(getCodec().toBinding(path, data));
+        } catch (DeserializationException e) {
+            return Optional.absent();
+        }
     }
 
     private class TranslatingDataChangeInvoker implements DOMDataChangeListener {
@@ -175,7 +200,8 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         }
 
         @Override
-        public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
+        public void onDataChanged(
+                final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
             bindingDataChangeListener.onDataChanged(new TranslatedDataChangeEvent(change, path));
         }
     }
@@ -235,7 +261,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         @Override
         public DataObject getOriginalSubtree() {
             if (originalDataCache == null) {
-                if (domEvent.getOriginalSubtree() != null) {
+                if(domEvent.getOriginalSubtree() != null) {
                     originalDataCache = toBindingData(path, domEvent.getOriginalSubtree());
                 } else {
                     originalDataCache = Optional.absent();
@@ -247,7 +273,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         @Override
         public DataObject getUpdatedSubtree() {
             if (updatedDataCache == null) {
-                if (domEvent.getUpdatedSubtree() != null) {
+                if(domEvent.getUpdatedSubtree() != null) {
                     updatedDataCache = toBindingData(path, domEvent.getUpdatedSubtree());
                 } else {
                     updatedDataCache = Optional.absent();
index 1e2d2b17f0b1846ab9272f6683f2a0f00cd1c070..66caaea7083af18f1ffaedc3113f4e35d167b4ff 100644 (file)
  */
 package org.opendaylight.controller.md.sal.binding.impl;
 
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
+import java.lang.reflect.Method;
 import java.util.AbstractMap.SimpleEntry;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class BindingToNormalizedNodeCodec implements SchemaContextListener,AutoCloseable {
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
 
     private final BindingIndependentMappingService bindingToLegacy;
-    private final BindingNormalizedNodeCodecRegistry codecRegistry;
     private DataNormalizer legacyToNormalized;
-    private final GeneratedClassLoadingStrategy classLoadingStrategy;
 
-    public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy, final BindingIndependentMappingService mappingService, final BindingNormalizedNodeCodecRegistry codecRegistry) {
+    public BindingToNormalizedNodeCodec(final BindingIndependentMappingService mappingService) {
         super();
         this.bindingToLegacy = mappingService;
-        this.classLoadingStrategy = classLoadingStrategy;
-        this.codecRegistry = codecRegistry;
-
     }
 
     public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier toNormalized(
             final InstanceIdentifier<? extends DataObject> binding) {
-        return codecRegistry.toYangInstanceIdentifier(binding);
+
+        // Used instance-identifier codec do not support serialization of last
+        // path
+        // argument if it is Augmentation (behaviour expected by old datastore)
+        // in this case, we explicitly check if last argument is augmentation
+        // to process it separately
+        if (isAugmentationIdentifier(binding)) {
+            return toNormalizedAugmented(binding);
+        }
+        return toNormalizedImpl(binding);
     }
 
-    @SuppressWarnings({ "unchecked", "rawtypes" })
     public Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
             final InstanceIdentifier<? extends DataObject> bindingPath, final DataObject bindingObject) {
-        return codecRegistry.toNormalizedNode((InstanceIdentifier) bindingPath, bindingObject);
+        return toNormalizedNode(toBindingEntry(bindingPath, bindingObject));
 
     }
 
     public Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
             final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> binding) {
-        return toNormalizedNode(binding.getKey(),binding.getValue());
+        Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> legacyEntry = bindingToLegacy
+                .toDataDom(binding);
+        Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, NormalizedNode<?, ?>> normalizedEntry = legacyToNormalized
+                .toNormalized(legacyEntry);
+        LOG.trace("Serialization of {}, Legacy Representation: {}, Normalized Representation: {}", binding,
+                legacyEntry, normalizedEntry);
+        if (isAugmentation(binding.getKey().getTargetType())) {
+
+            for (DataContainerChild<? extends PathArgument, ?> child : ((DataContainerNode<?>) normalizedEntry
+                    .getValue()).getValue()) {
+                if (child instanceof AugmentationNode) {
+                    ImmutableList<PathArgument> childArgs = ImmutableList.<PathArgument> builder()
+                            .addAll(normalizedEntry.getKey().getPathArguments()).add(child.getIdentifier()).build();
+                    org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier childPath = org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier
+                            .create(childArgs);
+                    return toDOMEntry(childPath, child);
+                }
+            }
+
+        }
+        return normalizedEntry;
+
     }
 
     /**
@@ -75,13 +125,109 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener,AutoC
     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(
             final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized)
                     throws DeserializationException {
+
+        PathArgument lastArgument = Iterables.getLast(normalized.getPathArguments());
+        // Used instance-identifier codec do not support serialization of last
+        // path
+        // argument if it is AugmentationIdentifier (behaviour expected by old
+        // datastore)
+        // in this case, we explicitly check if last argument is augmentation
+        // to process it separately
+        if (lastArgument instanceof AugmentationIdentifier) {
+            return toBindingAugmented(normalized);
+        }
+        return toBindingImpl(normalized);
+    }
+
+    private Optional<InstanceIdentifier<? extends DataObject>> toBindingAugmented(
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized)
+                    throws DeserializationException {
+        Optional<InstanceIdentifier<? extends DataObject>> potential = toBindingImpl(normalized);
+        // Shorthand check, if codec already supports deserialization
+        // of AugmentationIdentifier we will return
+        if (potential.isPresent() && isAugmentationIdentifier(potential.get())) {
+            return potential;
+        }
+
+        int normalizedCount = getAugmentationCount(normalized);
+        AugmentationIdentifier lastArgument = (AugmentationIdentifier) Iterables.getLast(normalized.getPathArguments());
+
+        // Here we employ small trick - Binding-aware Codec injects an pointer
+        // to augmentation class
+        // if child is referenced - so we will reference child and then shorten
+        // path.
+        LOG.trace("Looking for candidates to match {}", normalized);
+        for (QName child : lastArgument.getPossibleChildNames()) {
+            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier childPath = normalized.node(child);
+            try {
+                if (isNotRepresentable(childPath)) {
+                    LOG.trace("Path {} is not BI-representable, skipping it", childPath);
+                    continue;
+                }
+            } catch (DataNormalizationException e) {
+                LOG.warn("Failed to denormalize path {}, skipping it", childPath, e);
+                continue;
+            }
+
+            Optional<InstanceIdentifier<? extends DataObject>> baId = toBindingImpl(childPath);
+            if (!baId.isPresent()) {
+                LOG.debug("No binding-aware identifier found for path {}, skipping it", childPath);
+                continue;
+            }
+
+            InstanceIdentifier<? extends DataObject> potentialPath = shortenToLastAugment(baId.get());
+            int potentialAugmentCount = getAugmentationCount(potentialPath);
+            if (potentialAugmentCount == normalizedCount) {
+                LOG.trace("Found matching path {}", potentialPath);
+                return Optional.<InstanceIdentifier<? extends DataObject>> of(potentialPath);
+            }
+
+            LOG.trace("Skipping mis-matched potential path {}", potentialPath);
+        }
+
+        LOG.trace("Failed to find augmentation matching {}", normalized);
+        return Optional.absent();
+    }
+
+    private Optional<InstanceIdentifier<? extends DataObject>> toBindingImpl(
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized)
+                    throws DeserializationException {
+        org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier legacyPath;
+
         try {
-            return  Optional.<InstanceIdentifier<? extends DataObject>>of(codecRegistry.fromYangInstanceIdentifier(normalized));
-        } catch (IllegalArgumentException e) {
-            return Optional.absent();
+            if (isNotRepresentable(normalized)) {
+                return Optional.absent();
+            }
+            legacyPath = legacyToNormalized.toLegacy(normalized);
+        } catch (DataNormalizationException e) {
+            throw new IllegalStateException("Could not denormalize path.", e);
+        }
+        LOG.trace("InstanceIdentifier Path Deserialization: Legacy representation {}, Normalized representation: {}",
+                legacyPath, normalized);
+        return Optional.<InstanceIdentifier<? extends DataObject>> of(bindingToLegacy.fromDataDom(legacyPath));
+    }
+
+    private boolean isNotRepresentable(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized)
+            throws DataNormalizationException {
+        DataNormalizationOperation<?> op = findNormalizationOperation(normalized);
+        if (op.isMixin() && op.getIdentifier() instanceof NodeIdentifier) {
+            return true;
+        }
+        if (op.isLeaf()) {
+            return true;
         }
+        return false;
     }
 
+    private DataNormalizationOperation<?> findNormalizationOperation(
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized)
+                    throws DataNormalizationException {
+        DataNormalizationOperation<?> current = legacyToNormalized.getRootOperation();
+        for (PathArgument arg : normalized.getPathArguments()) {
+            current = current.getChild(arg);
+        }
+        return current;
+    }
 
     private static final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> toBindingEntry(
             final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> key,
@@ -90,19 +236,45 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener,AutoC
                 key, value);
     }
 
+    private static final Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, NormalizedNode<?, ?>> toDOMEntry(
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier key, final NormalizedNode<?, ?> value) {
+        return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, NormalizedNode<?, ?>>(key,
+                value);
+    }
+
+    public DataObject toBinding(final InstanceIdentifier<?> path, final NormalizedNode<?, ?> normalizedNode)
+            throws DeserializationException {
+        CompositeNode legacy = null;
+        if (isAugmentationIdentifier(path) && normalizedNode instanceof AugmentationNode) {
+            QName augIdentifier = BindingReflections.findQName(path.getTargetType());
+            ContainerNode virtualNode = Builders.containerBuilder() //
+                    .withNodeIdentifier(new NodeIdentifier(augIdentifier)) //
+                    .withChild((DataContainerChild<?, ?>) normalizedNode) //
+                    .build();
+            legacy = (CompositeNode) DataNormalizer.toLegacy(virtualNode);
+        } else {
+            legacy = (CompositeNode) DataNormalizer.toLegacy(normalizedNode);
+        }
+
+        return bindingToLegacy.dataObjectFromDataDom(path, legacy);
+    }
+
     public DataNormalizer getDataNormalizer() {
         return legacyToNormalized;
     }
 
-    @SuppressWarnings("unchecked")
     public Optional<Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
             final Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
                     throws DeserializationException {
-        try {
-            @SuppressWarnings("rawtypes")
-            Entry binding = codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue());
-            return Optional.<Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>>fromNullable(binding);
-        } catch (IllegalArgumentException e) {
+        Optional<InstanceIdentifier<? extends DataObject>> potentialPath = toBinding(normalized.getKey());
+        if (potentialPath.isPresent()) {
+            InstanceIdentifier<? extends DataObject> bindingPath = potentialPath.get();
+            DataObject bindingData = toBinding(bindingPath, normalized.getValue());
+            if (bindingData == null) {
+                LOG.warn("Failed to deserialize {} to Binding format. Binding path is: {}", normalized, bindingPath);
+            }
+            return Optional.of(toBindingEntry(bindingPath, bindingData));
+        } else {
             return Optional.absent();
         }
     }
@@ -110,11 +282,269 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener,AutoC
     @Override
     public void onGlobalContextUpdated(final SchemaContext arg0) {
         legacyToNormalized = new DataNormalizer(arg0);
-        codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(classLoadingStrategy, arg0));
     }
 
+    private org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier toNormalizedAugmented(
+            final InstanceIdentifier<?> augPath) {
+        org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier processed = toNormalizedImpl(augPath);
+        // If used instance identifier codec added supports for deserialization
+        // of last AugmentationIdentifier we will just reuse it
+        if (isAugmentationIdentifier(processed)) {
+            return processed;
+        }
+        Optional<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier> additionalSerialized;
+        additionalSerialized = toNormalizedAugmentedUsingChildContainers(augPath, processed);
+
+        if (additionalSerialized.isPresent()) {
+            return additionalSerialized.get();
+        }
+        additionalSerialized = toNormalizedAugmentedUsingChildLeafs(augPath, processed);
+        if (additionalSerialized.isPresent()) {
+            return additionalSerialized.get();
+        }
+        throw new IllegalStateException("Unabled to construct augmentation identfier for " + augPath);
+    }
+
+    /**
+     * Tries to find correct augmentation identifier using children leafs
+     *
+     * This method uses normalized Instance Identifier of parent node to fetch
+     * schema and {@link BindingReflections#getModuleInfo(Class)} to learn about
+     * augmentation namespace, specificly, in which module it was defined.
+     *
+     * Then it uses it to filter all available augmentations for parent by
+     * module. After that it walks augmentations in particular module and
+     * pick-up first which at least one leaf name matches supplied augmentation.
+     * We could do this safely since YANG explicitly states that no any existing
+     * augmentations must differ in leaf fully qualified names.
+     *
+     *
+     * @param augPath
+     *            Binding Aware Path which ends with augment
+     * @param parentPath
+     *            Processed path
+     * @return
+     */
+    private Optional<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier> toNormalizedAugmentedUsingChildLeafs(
+            final InstanceIdentifier<?> augPath,
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier parentPath) {
+        try {
+            DataNormalizationOperation<?> parentOp = legacyToNormalized.getOperation(parentPath);
+            if(!parentOp.getDataSchemaNode().isPresent()) {
+                return Optional.absent();
+            }
+            DataSchemaNode parentSchema = parentOp.getDataSchemaNode().get();
+            if (parentSchema instanceof AugmentationTarget) {
+                Set<AugmentationSchema> augmentations = ((AugmentationTarget) parentSchema).getAvailableAugmentations();
+                LOG.info("Augmentations for {}, {}", augPath, augmentations);
+                Optional<AugmentationSchema> schema = findAugmentation(augPath.getTargetType(), augmentations);
+                if (schema.isPresent()) {
+                    AugmentationIdentifier augmentationIdentifier = DataNormalizationOperation
+                            .augmentationIdentifierFrom(schema.get());
+                    return Optional.of(parentPath.node(augmentationIdentifier));
+                }
+            }
+        } catch (DataNormalizationException e) {
+            throw new IllegalArgumentException(e);
+        }
+        return Optional.absent();
+    }
+
+    /**
+     * Creates instance identifier for augmentation child, tries to serialize it
+     * Instance Identifier is then shortened to last augmentation.
+     *
+     * This is for situations, where underlying codec is implementing hydrogen
+     * style DOM APIs (which did not supported {@link AugmentationIdentifier}.)
+     *
+     * @param augPath
+     * @param parentPath
+     *            Path to parent node
+     * @return
+     */
+    @SuppressWarnings("rawtypes")
+    private Optional<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier> toNormalizedAugmentedUsingChildContainers(
+            final InstanceIdentifier<?> augPath,
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier parentPath) {
+        for (Class augChild : BindingReflections.getChildrenClasses(augPath.getTargetType())) {
+            @SuppressWarnings("unchecked")
+            InstanceIdentifier<?> childPath = augPath.child(augChild);
+            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized = toNormalizedImpl(childPath);
+            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier potentialDiscovered = shortenToLastAugmentation(
+                    normalized, parentPath);
+            if (potentialDiscovered != null) {
+                return Optional.of(potentialDiscovered);
+            }
+        }
+        return Optional.absent();
+    }
+
+    private Optional<AugmentationSchema> findAugmentation(final Class<?> targetType,
+            final Set<AugmentationSchema> augmentations) {
+        YangModuleInfo moduleInfo;
+        try {
+            moduleInfo = BindingReflections.getModuleInfo(targetType);
+        } catch (Exception e) {
+            throw new IllegalStateException(e);
+        }
+        Iterable<AugmentationSchema> filtered = filteredByModuleInfo(augmentations,
+                BindingReflections.getModuleQName(moduleInfo).getModule());
+        filtered.toString();
+        Set<String> targetTypeGetters = getYangModeledGetters(targetType);
+        for (AugmentationSchema schema : filtered) {
+            for (DataSchemaNode child : schema.getChildNodes()) {
+                String getterName = "get" + BindingMapping.getClassName(child.getQName());
+                if (targetTypeGetters.contains(getterName)) {
+                    return Optional.of(schema);
+                }
+            }
+        }
+        return Optional.absent();
+    }
+
+    private static Iterable<AugmentationSchema> filteredByModuleInfo(final Iterable<AugmentationSchema> augmentations,
+            final QNameModule module) {
+        return Iterables.filter(augmentations, new Predicate<AugmentationSchema>() {
+            @Override
+            public boolean apply(final AugmentationSchema schema) {
+                final Collection<DataSchemaNode> childNodes = schema.getChildNodes();
+                return !childNodes.isEmpty() && module.equals(Iterables.get(childNodes, 0).getQName().getModule());
+            }
+        });
+    }
+
+    public static final Set<String> getYangModeledGetters(final Class<?> targetType) {
+        HashSet<String> ret = new HashSet<String>();
+        for (Method method : targetType.getMethods()) {
+            if (isYangModeledGetter(method)) {
+                ret.add(method.getName());
+            }
+        }
+        return ret;
+    }
+
+    /**
+     *
+     * Returns true if supplied method represent getter for YANG modeled value
+     *
+     * @param method
+     *            Method to be tested
+     * @return true if method represent getter for YANG Modeled value.
+     */
+    private static final boolean isYangModeledGetter(final Method method) {
+        return !method.getName().equals("getClass") && !method.getName().equals("getImplementedInterface")
+                && method.getName().startsWith("get") && method.getParameterTypes().length == 0;
+    }
+
+    private org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier shortenToLastAugmentation(
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized,
+            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier parentPath) {
+        int parentSize = Iterables.size(parentPath.getPathArguments());
+        int position = 0;
+        int foundPosition = -1;
+        for (PathArgument arg : normalized.getPathArguments()) {
+            position++;
+            if (arg instanceof AugmentationIdentifier) {
+                foundPosition = position;
+            }
+        }
+        if (foundPosition > 0 && foundPosition > parentSize) {
+            Iterable<PathArgument> shortened = Iterables.limit(normalized.getPathArguments(), foundPosition);
+            return org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.create(shortened);
+        }
+        return null;
+    }
+
+    private InstanceIdentifier<? extends DataObject> shortenToLastAugment(
+            final InstanceIdentifier<? extends DataObject> binding) {
+        int position = 0;
+        int foundPosition = -1;
+        for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : binding.getPathArguments()) {
+            position++;
+            if (isAugmentation(arg.getType())) {
+                foundPosition = position;
+            }
+        }
+        return InstanceIdentifier.create(Iterables.limit(binding.getPathArguments(), foundPosition));
+    }
+
+    private org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier toNormalizedImpl(
+            final InstanceIdentifier<? extends DataObject> binding) {
+        final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier legacyPath = bindingToLegacy
+                .toDataDom(binding);
+        final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier normalized = legacyToNormalized
+                .toNormalized(legacyPath);
+        return normalized;
+    }
+
+    private static boolean isAugmentation(final Class<? extends DataObject> type) {
+        return Augmentation.class.isAssignableFrom(type);
+    }
+
+    private static boolean isAugmentationIdentifier(final InstanceIdentifier<?> potential) {
+        return Augmentation.class.isAssignableFrom(potential.getTargetType());
+    }
+
+    private boolean isAugmentationIdentifier(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier processed) {
+        return Iterables.getLast(processed.getPathArguments()) instanceof AugmentationIdentifier;
+    }
+
+    private static int getAugmentationCount(final InstanceIdentifier<?> potential) {
+        int count = 0;
+        for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : potential.getPathArguments()) {
+            if (isAugmentation(arg.getType())) {
+                count++;
+            }
+
+        }
+        return count;
+    }
+
+    private static int getAugmentationCount(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier potential) {
+        int count = 0;
+        for (PathArgument arg : potential.getPathArguments()) {
+            if (arg instanceof AugmentationIdentifier) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>  deserializeFunction(final InstanceIdentifier<T> path) {
-        return codecRegistry.deserializeFunction(path);
+        return new DeserializeFunction(this, path);
+    }
+
+    private static class DeserializeFunction<T extends DataObject> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
+
+        private final BindingToNormalizedNodeCodec codec;
+        private final InstanceIdentifier<?> path;
+
+        public DeserializeFunction(final BindingToNormalizedNodeCodec codec, final InstanceIdentifier<?> path) {
+            super();
+            this.codec = Preconditions.checkNotNull(codec, "Codec must not be null");
+            this.path = Preconditions.checkNotNull(path, "Path must not be null");
+        }
+
+        @SuppressWarnings("rawtypes")
+        @Nullable
+        @Override
+        public Optional apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
+            if (normalizedNode.isPresent()) {
+                final DataObject dataObject;
+                try {
+                    dataObject = codec.toBinding(path, normalizedNode.get());
+                } catch (DeserializationException e) {
+                    LOG.warn("Failed to create dataobject from node {}", normalizedNode.get(), e);
+                    throw new IllegalStateException("Failed to create dataobject", e);
+                }
+
+                if (dataObject != null) {
+                    return Optional.of(dataObject);
+                }
+            }
+            return Optional.absent();
+        }
     }
 
     /**
@@ -136,13 +566,4 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener,AutoC
         }
         return currentOp.createDefault(path.getLastPathArgument());
     }
-
-    public BindingIndependentMappingService getLegacy() {
-        return bindingToLegacy;
-    }
-
-    @Override
-    public void close() throws Exception {
-        // NOOP Intentionally
-    }
 }
index 52e114b0ea969436bd4ea2928babf0df7e5f9b96..237d9678f95f3a743dfbe19a033ca02845b81375 100644 (file)
@@ -7,12 +7,6 @@
  */
 package org.opendaylight.controller.md.sal.binding.impl;
 
-import com.google.common.base.Function;
-import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -23,6 +17,7 @@ import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
+
 import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
@@ -49,9 +44,17 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Function;
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+
 @SuppressWarnings("deprecation")
 public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDataBroker implements DataProviderService, AutoCloseable {
 
@@ -61,7 +64,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
     private final ListeningExecutorService executorService;
 
     public ForwardedBackwardsCompatibleDataBroker(final DOMDataBroker domDataBroker,
-            final BindingToNormalizedNodeCodec mappingService, final SchemaService schemaService,final ListeningExecutorService executor) {
+            final BindingIndependentMappingService mappingService, final SchemaService schemaService,final ListeningExecutorService executor) {
         super(domDataBroker, mappingService,schemaService);
         executorService = executor;
         LOG.info("ForwardedBackwardsCompatibleBroker started.");
index ef66d80ed445b1e323dc5c2ad770236e42eb64a8..6359b60684ef45e18d2185d1231b14b165497724 100644 (file)
@@ -16,6 +16,7 @@ import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 
 /**
  * The DataBrokerImpl simply defers to the DOMDataBroker for all its operations.
@@ -29,8 +30,8 @@ import org.opendaylight.controller.sal.core.api.model.SchemaService;
  */
 public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker implements DataBroker {
 
-    public ForwardedBindingDataBroker(final DOMDataBroker domDataBroker, final BindingToNormalizedNodeCodec codec, final SchemaService schemaService) {
-        super(domDataBroker, codec,schemaService);
+    public ForwardedBindingDataBroker(final DOMDataBroker domDataBroker, final BindingIndependentMappingService mappingService, final SchemaService schemaService) {
+        super(domDataBroker, mappingService,schemaService);
     }
 
     @Override
index f037e679be72fbb037318708c98217325782dd66..1ec4aa2d30bc9da7307891a41050bfc33e55642a 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.controller.sal.binding.codegen.impl;
 
-import com.google.common.util.concurrent.ForwardingBlockingQueue;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -20,19 +16,24 @@ import java.util.concurrent.RejectedExecutionHandler;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+
 import javassist.ClassPool;
+
 import org.apache.commons.lang3.StringUtils;
 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
 import org.opendaylight.controller.sal.binding.spi.NotificationInvokerFactory;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.util.concurrent.ForwardingBlockingQueue;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
 public class SingletonHolder {
     private static final Logger logger = LoggerFactory.getLogger(SingletonHolder.class);
 
     public static final ClassPool CLASS_POOL = ClassPool.getDefault();
-    public static final JavassistUtils JAVASSIST = JavassistUtils.forClassPool(CLASS_POOL);
     public static final org.opendaylight.controller.sal.binding.codegen.impl.RuntimeCodeGenerator RPC_GENERATOR_IMPL = new org.opendaylight.controller.sal.binding.codegen.impl.RuntimeCodeGenerator(
             CLASS_POOL);
     public static final RuntimeCodeGenerator RPC_GENERATOR = RPC_GENERATOR_IMPL;
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootDataBrokerImpl.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootDataBrokerImpl.java
new file mode 100644 (file)
index 0000000..a1cae26
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * 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
+ */
+package org.opendaylight.controller.sal.binding.impl;\r
+\r
+import org.opendaylight.controller.config.yang.md.sal.binding.impl.Data;\r
+import org.opendaylight.controller.config.yang.md.sal.binding.impl.DataBrokerImplRuntimeMXBean;\r
+import org.opendaylight.controller.config.yang.md.sal.binding.impl.DataBrokerImplRuntimeRegistration;\r
+import org.opendaylight.controller.config.yang.md.sal.binding.impl.DataBrokerImplRuntimeRegistrator;\r
+import org.opendaylight.controller.config.yang.md.sal.binding.impl.Transactions;\r
+import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndependentConnector;\r
+\r
+public class RootDataBrokerImpl extends DataBrokerImpl implements DataBrokerImplRuntimeMXBean {\r
+\r
+    private final Transactions transactions = new Transactions();\r
+    private final Data data = new Data();\r
+    private BindingIndependentConnector bindingIndependentConnector;\r
+    private DataBrokerImplRuntimeRegistration runtimeBeanRegistration;\r
+\r
+    public BindingIndependentConnector getBindingIndependentConnector() {\r
+        return bindingIndependentConnector;\r
+    }\r
+\r
+    public Transactions getTransactions() {\r
+        transactions.setCreated(getCreatedTransactionsCount().get());\r
+        transactions.setSubmitted(getSubmittedTransactionsCount().get());\r
+        transactions.setSuccessful(getFinishedTransactionsCount().get());\r
+        transactions.setFailed(getFailedTransactionsCount().get());\r
+        return transactions;\r
+    }\r
+\r
+    @Override\r
+    public Data getData() {\r
+        data.setTransactions(getTransactions());\r
+        return data;\r
+    }\r
+\r
+    public void setBindingIndependentConnector(BindingIndependentConnector runtimeMapping) {\r
+        this.bindingIndependentConnector = runtimeMapping;\r
+    }\r
+\r
+    public void registerRuntimeBean(DataBrokerImplRuntimeRegistrator rootRegistrator) {\r
+        runtimeBeanRegistration = rootRegistrator.register(this);\r
+    }\r
+\r
+}\r
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/forward/DomForwardedDataBrokerImpl.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/forward/DomForwardedDataBrokerImpl.java
new file mode 100644 (file)
index 0000000..3d0e4de
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * 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
+ */
+package org.opendaylight.controller.sal.binding.impl.forward;
+
+import java.util.Collection;
+import java.util.Collections;
+
+import org.opendaylight.controller.sal.binding.impl.RootDataBrokerImpl;
+import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingDomConnectorDeployer;
+import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndependentConnector;
+import org.opendaylight.controller.sal.core.api.Provider;
+import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
+
+public class DomForwardedDataBrokerImpl extends RootDataBrokerImpl implements Provider, DomForwardedBroker {
+
+    private BindingIndependentConnector connector;
+    private ProviderSession domProviderContext;
+
+    public void setConnector(BindingIndependentConnector connector) {
+        this.connector = connector;
+    }
+
+    @Override
+    public void onSessionInitiated(ProviderSession session) {
+        this.setDomProviderContext(session);
+    }
+
+    @Override
+    public Collection<ProviderFunctionality> getProviderFunctionality() {
+        return Collections.emptySet();
+    }
+
+    @Override
+    public BindingIndependentConnector getConnector() {
+        return connector;
+    }
+
+    @Override
+    public ProviderSession getDomProviderContext() {
+        return domProviderContext;
+    }
+
+    public void setDomProviderContext(ProviderSession domProviderContext) {
+        this.domProviderContext = domProviderContext;
+    }
+
+    @Override
+    public void startForwarding() {
+        BindingDomConnectorDeployer.startDataForwarding(getConnector(), this, getDomProviderContext());
+    }
+}
index aec27235910633fb34389208e02b550c81a85a43..cee4b1efb3a3107e27fa5325dd6d3f92cc937609 100644 (file)
@@ -18,9 +18,10 @@ module opendaylight-sal-binding-broker-impl {
 
     identity binding-dom-mapping-service {
         base config:service-type;
-        config:java-class "org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec";
+        config:java-class "org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService";
     }
 
+
     identity binding-broker-impl {
         base config:module-type;
         config:provided-service sal:binding-broker-osgi-registry;
@@ -28,6 +29,13 @@ module opendaylight-sal-binding-broker-impl {
         config:java-name-prefix BindingBrokerImpl;
     }
 
+    identity binding-data-broker {
+        base config:module-type;
+        config:provided-service sal:binding-data-broker;
+        config:provided-service sal:binding-data-consumer-broker;
+        config:java-name-prefix DataBrokerImpl;
+    }
+
     identity binding-data-compatible-broker {
         base config:module-type;
         config:provided-service sal:binding-data-broker;
@@ -123,6 +131,29 @@ module opendaylight-sal-binding-broker-impl {
         }
     }
 
+    augment "/config:modules/config:module/config:configuration" {
+        case binding-data-broker {
+            when "/config:modules/config:module/config:type = 'binding-data-broker'";
+            container dom-broker {
+                uses config:service-ref {
+                    refine type {
+                        mandatory true;
+                        config:required-identity dom:dom-broker-osgi-registry;
+                    }
+                }
+            }
+
+            container mapping-service {
+                uses config:service-ref {
+                    refine type {
+                        mandatory true;
+                        config:required-identity binding-dom-mapping-service;
+                    }
+                }
+            }
+        }
+    }
+
     augment "/config:modules/config:module/config:configuration" {
         case binding-data-compatible-broker {
             when "/config:modules/config:module/config:type = 'binding-data-compatible-broker'";
@@ -147,6 +178,14 @@ module opendaylight-sal-binding-broker-impl {
         }
     }
 
+    augment "/config:modules/config:module/config:state" {
+        case binding-data-broker {
+            when "/config:modules/config:module/config:type = 'binding-data-broker'";
+            container data {
+                uses common:data-state;
+            }
+        }
+    }
     augment "/config:modules/config:module/config:state" {
         case binding-rpc-broker {
             when "/config:modules/config:module/config:type = 'binding-rpc-broker'";
index 815fc452594e837965b1bd7d66a1814cf87bf299..fd0a169694c5836b52fe02bc1207805cd071ffef 100644 (file)
@@ -1,8 +1,8 @@
 package org.opendaylight.controller.md.sal.binding.impl.test;
 
 import static org.junit.Assert.assertTrue;
-
 import javassist.ClassPool;
+
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
 import org.opendaylight.controller.md.sal.binding.test.AbstractSchemaAwareTest;
@@ -11,11 +11,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controll
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
@@ -38,9 +34,7 @@ public class BindingNormalizedCodecTest extends AbstractSchemaAwareTest {
     @Override
     protected void setupWithSchema(final SchemaContext context) {
         mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
-        StreamWriterGenerator streamWriter = new StreamWriterGenerator(JavassistUtils.forClassPool(ClassPool.getDefault()));
-        BindingNormalizedNodeCodecRegistry registry = new BindingNormalizedNodeCodecRegistry(streamWriter);
-        codec = new BindingToNormalizedNodeCodec(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), mappingService, registry);
+        codec = new BindingToNormalizedNodeCodec(mappingService);
         mappingService.onGlobalContextUpdated(context);
         codec.onGlobalContextUpdated(context);
     };
index 106fcea0e9f178470c26eab42fe1bf7c36eb4e08..60eec55ca55df3df580318e5608ea08f1a319801 100644 (file)
@@ -7,14 +7,9 @@
  */
 package org.opendaylight.controller.md.sal.binding.test;
 
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
 import javassist.ClassPool;
 
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker;
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -24,22 +19,20 @@ import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 import org.opendaylight.controller.sal.binding.test.util.MockSchemaService;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
 public class DataBrokerTestCustomizer {
 
     private DOMDataBroker domDataBroker;
     private final RuntimeGeneratedMappingServiceImpl mappingService;
     private final MockSchemaService schemaService;
     private ImmutableMap<LogicalDatastoreType, DOMStore> datastores;
-    private final BindingToNormalizedNodeCodec bindingToNormalized ;
 
     public ImmutableMap<LogicalDatastoreType, DOMStore> createDatastores() {
         return ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
@@ -50,13 +43,7 @@ public class DataBrokerTestCustomizer {
 
     public DataBrokerTestCustomizer() {
         schemaService = new MockSchemaService();
-        ClassPool pool = ClassPool.getDefault();
-        mappingService = new RuntimeGeneratedMappingServiceImpl(pool);
-        DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
-        BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
-        GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
-        bindingToNormalized = new BindingToNormalizedNodeCodec(loading, mappingService, codecRegistry);
-        schemaService.registerSchemaContextListener(bindingToNormalized);
+        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
     }
 
     public DOMStore createConfigurationDatastore() {
@@ -82,13 +69,14 @@ public class DataBrokerTestCustomizer {
     }
 
     public DataBroker createDataBroker() {
-        return new ForwardedBindingDataBroker(getDOMDataBroker(), bindingToNormalized, schemaService );
+        return new ForwardedBindingDataBroker(getDOMDataBroker(), getMappingService(), getSchemaService());
     }
 
     public ForwardedBackwardsCompatibleDataBroker createBackwardsCompatibleDataBroker() {
-        return new ForwardedBackwardsCompatibleDataBroker(getDOMDataBroker(), bindingToNormalized, getSchemaService(), MoreExecutors.sameThreadExecutor());
+        return new ForwardedBackwardsCompatibleDataBroker(getDOMDataBroker(), getMappingService(), getSchemaService(), MoreExecutors.sameThreadExecutor());
     }
 
+
     private SchemaService getSchemaService() {
         return schemaService;
     }
index 63e0e2290aadd37e697d6a36d6de3fb779c3ab7f..7b67d3b10f4d2eacd2659eefdd1a72af2ca51482 100644 (file)
@@ -16,6 +16,7 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
@@ -75,7 +76,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
      *
      * @throws Exception
      */
-    @Test()
+    @Test( timeout = 15000)
     public void testAugmentSerialization() throws Exception {
 
         baDataService.registerDataChangeListener(NODES_INSTANCE_ID_BA, this);
@@ -121,7 +122,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
         testNodeRemove();
     }
 
-    private <T extends Augmentation<Node>> Node createTestNode(final Class<T> augmentationClass, final T augmentation) {
+    private <T extends Augmentation<Node>> Node createTestNode(Class<T> augmentationClass, T augmentation) {
         NodeBuilder nodeBuilder = new NodeBuilder();
         nodeBuilder.setId(new NodeId(NODE_ID));
         nodeBuilder.setKey(NODE_KEY);
@@ -129,7 +130,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
         return nodeBuilder.build();
     }
 
-    private DataModificationTransaction commitNodeAndVerifyTransaction(final Node original) throws Exception {
+    private DataModificationTransaction commitNodeAndVerifyTransaction(Node original) throws Exception {
         DataModificationTransaction transaction = baDataService.beginTransaction();
         transaction.putOperationalData(NODE_INSTANCE_ID_BA, original);
         RpcResult<TransactionStatus> result = transaction.commit().get();
@@ -147,7 +148,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
         assertNull(node);
     }
 
-    private AugmentationVerifier<Node> verifyNode(final Nodes nodes, final Node original) {
+    private AugmentationVerifier<Node> verifyNode(Nodes nodes, Node original) {
         assertNotNull(nodes);
         assertNotNull(nodes.getNode());
         assertEquals(1, nodes.getNode().size());
@@ -157,7 +158,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
         return new AugmentationVerifier<Node>(readedNode);
     }
 
-    private void assertBindingIndependentVersion(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier nodeId) {
+    private void assertBindingIndependentVersion(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier nodeId) {
         CompositeNode node = biDataService.readOperationalData(nodeId);
         assertNotNull(node);
     }
@@ -170,7 +171,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
         return nodeMeterStatistics(10, false);
     }
 
-    private NodeMeterStatistics nodeMeterStatistics(final int count, final boolean setDuration) {
+    private NodeMeterStatistics nodeMeterStatistics(int count, boolean setDuration) {
         NodeMeterStatisticsBuilder nmsb = new NodeMeterStatisticsBuilder();
         MeterStatisticsBuilder meterStats = new MeterStatisticsBuilder();
 
@@ -206,7 +207,7 @@ public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implem
     }
 
     @Override
-    public void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
+    public void onDataChanged(DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
         receivedChangeEvent = change;
     }
 
index d0a326adff83054ff99cbc9e0b1278dde8ed6ad4..fef5715f50deea8ac6038b8684dc832c779cf582 100644 (file)
@@ -9,19 +9,12 @@ package org.opendaylight.controller.sal.binding.test.util;
 
 import static com.google.common.base.Preconditions.checkState;
 
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ClassToInstanceMap;
-import com.google.common.collect.ImmutableClassToInstanceMap;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.MutableClassToInstanceMap;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
 import java.util.Set;
 import java.util.concurrent.Future;
+
 import javassist.ClassPool;
+
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker;
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -50,14 +43,9 @@ import org.opendaylight.controller.sal.core.spi.data.DOMStore;
 import org.opendaylight.controller.sal.dom.broker.BrokerImpl;
 import org.opendaylight.controller.sal.dom.broker.MountPointManagerImpl;
 import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
-import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -68,6 +56,15 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ClassToInstanceMap;
+import com.google.common.collect.ImmutableClassToInstanceMap;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.MutableClassToInstanceMap;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
 @Beta
 public class BindingTestContext implements AutoCloseable {
 
@@ -77,7 +74,6 @@ public class BindingTestContext implements AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(BindingTestContext.class);
 
     private RuntimeGeneratedMappingServiceImpl mappingServiceImpl;
-    private BindingToNormalizedNodeCodec codec;
 
     private DomForwardedBindingBrokerImpl baBrokerImpl;
     private DataBrokerImpl baDataImpl;
@@ -133,7 +129,7 @@ public class BindingTestContext implements AutoCloseable {
     public void startNewDataBroker() {
         checkState(executor != null, "Executor needs to be set");
         checkState(newDOMDataBroker != null, "DOM Data Broker must be set");
-        dataBroker = new ForwardedBindingDataBroker(newDOMDataBroker, codec, mockSchemaService);
+        dataBroker = new ForwardedBindingDataBroker(newDOMDataBroker, mappingServiceImpl, mockSchemaService);
     }
 
     public void startNewDomDataBroker() {
@@ -254,12 +250,6 @@ public class BindingTestContext implements AutoCloseable {
         checkState(classPool != null, "ClassPool needs to be present");
         mappingServiceImpl = new RuntimeGeneratedMappingServiceImpl(classPool);
         mockSchemaService.registerSchemaContextListener(mappingServiceImpl);
-
-        DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(classPool));
-        BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
-        GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
-        codec = new BindingToNormalizedNodeCodec(loading, mappingServiceImpl, codecRegistry);
-        mockSchemaService.registerSchemaContextListener(codec);
     }
 
     private void updateYangSchema(final ImmutableSet<YangModuleInfo> moduleInfos) {
@@ -290,7 +280,7 @@ public class BindingTestContext implements AutoCloseable {
     }
 
     public void startNewBindingDataBroker() {
-        ForwardedBackwardsCompatibleDataBroker forwarded = new ForwardedBackwardsCompatibleDataBroker(newDOMDataBroker, codec,mockSchemaService, executor);
+        ForwardedBackwardsCompatibleDataBroker forwarded = new ForwardedBackwardsCompatibleDataBroker(newDOMDataBroker, mappingServiceImpl,mockSchemaService, executor);
         baData = forwarded;
     }
 
index 344694381a222850fb23ccac0cc8415b3296f472..83a69969b7b8c8bd0be90111227bda05cd61fd58 100644 (file)
@@ -112,7 +112,6 @@ public class TestHelper {
                 mavenBundle(YANGTOOLS, "binding-generator-api").versionAsInProject(), mavenBundle(YANGTOOLS,
                         "binding-generator-spi").versionAsInProject(), //
                 mavenBundle(YANGTOOLS, "binding-generator-impl").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "binding-data-codec").versionAsInProject(),
                 mavenBundle(YANGTOOLS + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), // //
 
                 mavenBundle(CONTROLLER, "sal-core-api").versionAsInProject().update(), //
index 33039ea2314329e0a132606bff58894e7cb84585..8a390b337e1849ae8cf2c15f7799073ace928ee2 100644 (file)
@@ -11,10 +11,9 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
-import com.google.inject.Inject;
 import java.util.concurrent.Future;
+
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
@@ -23,6 +22,7 @@ import org.opendaylight.controller.sal.binding.api.data.DataBrokerService;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
@@ -31,6 +31,8 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
+import com.google.inject.Inject;
+
 public class DataServiceTest extends AbstractTest {
 
     protected DataBrokerService consumerDataService;
@@ -43,20 +45,12 @@ public class DataServiceTest extends AbstractTest {
     public void setUp() throws Exception {
     }
 
-    /*
-     *
-     * Ignored this, because classes here are constructed from
-     * very different class loader as MD-SAL is run into,
-     * this is code is run from different classloader.
-     *
-     */
     @Test
-    @Ignore
     public void test() throws Exception {
         BindingAwareConsumer consumer1 = new BindingAwareConsumer() {
 
             @Override
-            public void onSessionInitialized(final ConsumerContext session) {
+            public void onSessionInitialized(ConsumerContext session) {
                 consumerDataService = session.getSALService(DataBrokerService.class);
             }
         };
@@ -68,12 +62,12 @@ public class DataServiceTest extends AbstractTest {
         DataModificationTransaction transaction = consumerDataService.beginTransaction();
         assertNotNull(transaction);
 
-        InstanceIdentifier<Node> node1 = createNodeRef("0");
-        DataObject  node = consumerDataService.readConfigurationData(node1);
+        NodeRef node1 = createNodeRef("0");
+        DataObject  node = consumerDataService.readConfigurationData(node1.getValue());
         assertNull(node);
         Node nodeData1 = createNode("0");
 
-        transaction.putConfigurationData(node1, nodeData1);
+        transaction.putConfigurationData(node1.getValue(), nodeData1);
         Future<RpcResult<TransactionStatus>> commitResult = transaction.commit();
         assertNotNull(commitResult);
 
@@ -83,7 +77,7 @@ public class DataServiceTest extends AbstractTest {
         assertNotNull(result.getResult());
         assertEquals(TransactionStatus.COMMITED, result.getResult());
 
-        Node readedData = (Node) consumerDataService.readConfigurationData(node1);
+        Node readedData = (Node) consumerDataService.readConfigurationData(node1.getValue());
         assertNotNull(readedData);
         assertEquals(nodeData1.getKey(), readedData.getKey());
 
@@ -91,7 +85,7 @@ public class DataServiceTest extends AbstractTest {
         DataModificationTransaction transaction2 = consumerDataService.beginTransaction();
         assertNotNull(transaction);
 
-        transaction2.removeConfigurationData(node1);
+        transaction2.removeConfigurationData(node1.getValue());
 
         Future<RpcResult<TransactionStatus>> commitResult2 = transaction2.commit();
         assertNotNull(commitResult2);
@@ -102,19 +96,21 @@ public class DataServiceTest extends AbstractTest {
         assertNotNull(result2.getResult());
         assertEquals(TransactionStatus.COMMITED, result2.getResult());
 
-        DataObject readedData2 = consumerDataService.readConfigurationData(node1);
+        DataObject readedData2 = consumerDataService.readConfigurationData(node1.getValue());
         assertNull(readedData2);
 
 
     }
 
 
-    private static InstanceIdentifier<Node> createNodeRef(final String string) {
+    private static NodeRef createNodeRef(String string) {
         NodeKey key = new NodeKey(new NodeId(string));
-        return  InstanceIdentifier.builder(Nodes.class).child(Node.class, key).build();
+        InstanceIdentifier<Node> path = InstanceIdentifier.builder(Nodes.class).child(Node.class, key).build();
+
+        return new NodeRef(path);
     }
 
-    private static Node createNode(final String string) {
+    private static Node createNode(String string) {
         NodeBuilder ret = new NodeBuilder();
         NodeId id = new NodeId(string);
         ret.setKey(new NodeKey(id));
index 5e37f36a2c1d6e16c85696315d5427e1a2f2d9de..63a921d6f309db37a0a438bbadbafdaadb528485 100644 (file)
                 <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
                     <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:schema-service-singleton</type>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
+                                prefix:schema-service-singleton
+                            </type>
                             <name>yang-schema-service</name>
                         </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:runtime-generated-mapping</type>
-                            <name>runtime-mapping-singleton</name>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
+                                prefix:hash-map-data-store
+                            </type>
+                            <name>hash-map-data-store</name>
                         </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-notification-broker</type>
-                            <name>binding-notification-broker</name>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
+                                prefix:dom-broker-impl
+                            </type>
+                            <name>dom-broker</name>
+                            <data-store xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
+                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
+                                    dom:dom-data-store
+                                </type>
+                                <name>ref_hash-map-data-store</name>
+                            </data-store>
                         </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-broker-impl</type>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                prefix:binding-broker-impl
+                            </type>
                             <name>binding-broker-impl</name>
-                            <notification-service 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-notification-service</type>
-                                <name>binding-notification-broker</name>
+                            <notification-service
+                                    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-notification-service
+                                </type>
+                                <name>ref_binding-notification-broker</name>
                             </notification-service>
                             <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-data-broker</type>
-                                <name>binding-data-broker</name>
+                                <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
+                                    binding:binding-data-broker
+                                </type>
+                                <name>ref_binding-data-broker</name>
                             </data-broker>
                         </module>
-                        <!--
-                             Tree-based in-memory data store. This is the data store which is currently
-                             recommended for single-node deployments.
-                        -->
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:dom-inmemory-data-broker</type>
-                            <name>inmemory-data-broker</name>
-                            <schema-service>
-                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
-                                <name>yang-schema-service</name>
-                            </schema-service>
-                        </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:dom-broker-impl</type>
-                            <name>inmemory-dom-broker</name>
-                            <async-data-broker>
-                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
-                                <name>inmemory-data-broker</name>
-                            </async-data-broker>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                prefix:runtime-generated-mapping
+                            </type>
+                            <name>runtime-mapping-singleton</name>
                         </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-data-compatible-broker</type>
-                            <name>inmemory-binding-data-broker</name>
-                            <dom-async-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
-                                <name>dom-broker</name>
-                            </dom-async-broker>
-                            <binding-mapping-service 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:impl">binding:binding-dom-mapping-service</type>
-                                <name>runtime-mapping-singleton</name>
-                            </binding-mapping-service>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                prefix:binding-notification-broker
+                            </type>
+                            <name>binding-notification-broker</name>
                         </module>
                         <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-forwarded-data-broker</type>
-                            <name>binding-async-data-broker</name>
-                            <binding-forwarded-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <dom-async-broker>
-                                    <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
-                                    <name>dom-broker</name>
-                                </dom-async-broker>
-                                <binding-mapping-service>
-                                    <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
-                                    <name>runtime-mapping-singleton</name>
-                                </binding-mapping-service>
-                            </binding-forwarded-data-broker>
+                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                prefix:binding-data-broker
+                            </type>
+                            <name>binding-data-broker</name>
+                            <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
+                                    dom:dom-broker-osgi-registry
+                                </type>
+                                <name>ref_dom-broker</name>
+                            </dom-broker>
+                            <mapping-service 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:impl">
+                                    binding:binding-dom-mapping-service
+                                </type>
+                                <name>ref_runtime-mapping-singleton</name>
+                            </mapping-service>
                         </module>
                     </modules>
 
                     <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
                         <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
+                                dom:schema-service
+                            </type>
                             <instance>
-                                <name>yang-schema-service</name>
-                                <provider>/modules/module[type='schema-service-singleton'][name='yang-schema-service']</provider>
+                                <name>ref_yang-schema-service</name>
+                                <provider>
+                                    /config/modules/module[name='schema-service-singleton']/instance[name='yang-schema-service']
+                                </provider>
                             </instance>
                         </service>
                         <service>
-                            <type xmlns:binding-impl="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding-impl:binding-dom-mapping-service</type>
+                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
+                                binding:binding-notification-service
+                            </type>
                             <instance>
-                                <name>runtime-mapping-singleton</name>
-                                <provider>/modules/module[type='runtime-generated-mapping'][name='runtime-mapping-singleton']</provider>
+                                <name>ref_binding-notification-broker</name>
+                                <provider>
+                                    /config/modules/module[name='binding-notification-broker']/instance[name='binding-notification-broker']
+                                </provider>
                             </instance>
                         </service>
                         <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-notification-service</type>
+                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
+                                dom:dom-data-store
+                            </type>
                             <instance>
-                                <name>binding-notification-broker</name>
-                                <provider>/modules/module[type='binding-notification-broker'][name='binding-notification-broker']</provider>
+                                <name>ref_hash-map-data-store</name>
+                                <provider>
+                                    /config/modules/module[name='hash-map-data-store']/instance[name='hash-map-data-store']
+                                </provider>
                             </instance>
                         </service>
+
                         <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-broker-osgi-registry</type>
+                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
+                                binding:binding-broker-osgi-registry
+                            </type>
                             <instance>
-                                <name>binding-osgi-broker</name>
-                                <provider>/modules/module[type='binding-broker-impl'][name='binding-broker-impl']</provider>
+                                <name>ref_binding-broker-impl</name>
+                                <provider>
+                                    /config/modules/module[name='binding-broker-impl']/instance[name='binding-broker-impl']
+                                </provider>
                             </instance>
                         </service>
                         <service>
                                 <provider>/modules/module[type='binding-broker-impl'][name='binding-broker-impl']</provider>
                             </instance>
                         </service>
-
-                        <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
-                            <instance>
-                                <name>dom-broker</name>
-                                <provider>/modules/module[type='dom-broker-impl'][name='inmemory-dom-broker']</provider>
-                            </instance>
-                        </service>
-
                         <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
+                            <type xmlns:binding-impl="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                                binding-impl:binding-dom-mapping-service
+                            </type>
                             <instance>
-                                <name>binding-data-broker</name>
-                                <provider>/modules/module[type='binding-data-compatible-broker'][name='inmemory-binding-data-broker']</provider>
+                                <name>ref_runtime-mapping-singleton</name>
+                                <provider>
+                                    /config/modules/module[name='runtime-generated-mapping']/instance[name='runtime-mapping-singleton']
+                                </provider>
                             </instance>
                         </service>
-
                         <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-async-data-broker</type>
+                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
+                                dom:dom-broker-osgi-registry
+                            </type>
                             <instance>
-                                <name>binding-data-broker</name>
-                                <provider>/modules/module[type='binding-forwarded-data-broker'][name='binding-async-data-broker']</provider>
+                                <name>ref_dom-broker</name>
+                                <provider>/config/modules/module[name='dom-broker-impl']/instance[name='dom-broker']
+                                </provider>
                             </instance>
                         </service>
-
                         <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-async-data-broker</type>
+                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
+                                binding:binding-data-broker
+                            </type>
                             <instance>
-                                <name>inmemory-data-broker</name>
-                                <provider>/modules/module[type='dom-inmemory-data-broker'][name='inmemory-data-broker']</provider>
+                                <name>ref_binding-data-broker</name>
+                                <provider>
+                                    /config/modules/module[name='binding-data-broker']/instance[name='binding-data-broker']
+                                </provider>
                             </instance>
                         </service>
                     </services>
index 674c5bf5a596bb03a34f785d854ffdb305aac12b..38ec5f5ac2afda90ac5e8ea9eb454574dd4de14d 100644 (file)
           </execution>
         </executions>
       </plugin>
+
+
+
     </plugins>
   </build>
   <scm>
index 1f1a0f5cc6bde65f8b450aa90020593664752483..da0d62897a9d77cdbf6273acd7a80fdc7e11c6e0 100644 (file)
@@ -16,4 +16,5 @@ public class ActorConstants {
 
   public static final String RPC_BROKER_PATH= "/user/rpc/rpc-broker";
   public static final String RPC_REGISTRY_PATH = "/user/rpc/rpc-registry";
+  public static final String RPC_MANAGER_PATH = "/user/rpc";
 }
index d384144f4fde6389861597777bd795b30478e773..02e2d1201518b22001da9882e41ee881624a16bc 100644 (file)
@@ -4,7 +4,6 @@ import akka.actor.ActorRef;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import org.opendaylight.controller.remote.rpc.messages.ErrorResponse;
-import org.opendaylight.controller.remote.rpc.messages.InvokeRoutedRpc;
 import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
 import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
 import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
@@ -36,7 +35,7 @@ public class RemoteRpcImplementation implements RpcImplementation,
 
   @Override
   public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, YangInstanceIdentifier identifier, CompositeNode input) {
-    InvokeRoutedRpc rpcMsg = new InvokeRoutedRpc(rpc, identifier, input);
+    InvokeRpc rpcMsg = new InvokeRpc(rpc, identifier, input);
 
     return executeMsg(rpcMsg);
   }
@@ -49,7 +48,7 @@ public class RemoteRpcImplementation implements RpcImplementation,
 
   @Override
   public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
-    InvokeRpc rpcMsg = new InvokeRpc(rpc, input);
+    InvokeRpc rpcMsg = new InvokeRpc(rpc, null, input);
     return executeMsg(rpcMsg);
   }
 
@@ -57,7 +56,7 @@ public class RemoteRpcImplementation implements RpcImplementation,
     ListenableFuture<RpcResult<CompositeNode>> listenableFuture = null;
 
     try {
-      Object response = ActorUtil.executeLocalOperation(rpcBroker, rpcMsg, ActorUtil.ASK_DURATION, ActorUtil.AWAIT_DURATION);
+      Object response = ActorUtil.executeOperation(rpcBroker, rpcMsg, ActorUtil.ASK_DURATION, ActorUtil.AWAIT_DURATION);
       if(response instanceof RpcResponse) {
 
         RpcResponse rpcResponse = (RpcResponse) response;
@@ -74,7 +73,7 @@ public class RemoteRpcImplementation implements RpcImplementation,
 
       }
     } catch (Exception e) {
-      LOG.error("Error occurred while invoking RPC actor {}", e.toString());
+      LOG.error("Error occurred while invoking RPC actor {}", e);
 
       final RpcResultBuilder<CompositeNode> failed = RpcResultBuilder.failed();
       failed.withError(null, null, e.getMessage(), null, null, e.getCause());
index ac50b8fe5b0fcdcbfb9f78ef495308586a4a313c..d088f2284d65904cc90d3aa3d6f39a4ca2cc99aa 100644 (file)
@@ -12,8 +12,6 @@ package org.opendaylight.controller.remote.rpc;
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
 import org.opendaylight.controller.remote.rpc.messages.UpdateSchemaContext;
-import org.opendaylight.controller.remote.rpc.registry.ClusterWrapper;
-import org.opendaylight.controller.remote.rpc.registry.ClusterWrapperImpl;
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.controller.sal.core.api.Provider;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
@@ -64,11 +62,10 @@ public class RemoteRpcProvider implements AutoCloseable, Provider, SchemaContext
   private void start() {
     LOG.info("Starting all rpc listeners and actors.");
     // Create actor to handle and sync routing table in cluster
-    ClusterWrapper clusterWrapper = new ClusterWrapperImpl(actorSystem);
     SchemaService schemaService = brokerSession.getService(SchemaService.class);
     schemaContext = schemaService.getGlobalContext();
 
-    rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), ActorConstants.RPC_MANAGER);
+    rpcManager = actorSystem.actorOf(RpcManager.props(schemaContext, brokerSession, rpcProvisionRegistry), ActorConstants.RPC_MANAGER);
 
     LOG.debug("Rpc actors are created.");
   }
index a6eeac02708a20e8a746581d80c5054a776ed671..98cf6a329f655f3caeebb39b989a1b761ca9a5cd 100644 (file)
@@ -13,15 +13,14 @@ import akka.actor.ActorRef;
 import com.google.common.base.Preconditions;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
-import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRoutedRpc;
-import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
 import org.opendaylight.controller.sal.connector.api.RpcRouter;
 import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -29,23 +28,24 @@ import java.util.Set;
 public class RoutedRpcListener implements RouteChangeListener<RpcRoutingContext, YangInstanceIdentifier>{
   private static final Logger LOG = LoggerFactory.getLogger(RoutedRpcListener.class);
   private final ActorRef rpcRegistry;
-  private final String actorPath;
 
-  public RoutedRpcListener(ActorRef rpcRegistry, String actorPath) {
+  public RoutedRpcListener(ActorRef rpcRegistry) {
     Preconditions.checkNotNull(rpcRegistry, "rpc registry actor should not be null");
-    Preconditions.checkNotNull(actorPath, "actor path of rpc broker on current node should not be null");
 
     this.rpcRegistry = rpcRegistry;
-    this.actorPath = actorPath;
   }
 
   @Override
   public void onRouteChange(RouteChange<RpcRoutingContext, YangInstanceIdentifier> routeChange) {
     Map<RpcRoutingContext, Set<YangInstanceIdentifier>> announcements = routeChange.getAnnouncements();
-    announce(getRouteIdentifiers(announcements));
+    if(announcements != null && announcements.size() > 0){
+      announce(getRouteIdentifiers(announcements));
+    }
 
     Map<RpcRoutingContext, Set<YangInstanceIdentifier>> removals = routeChange.getRemovals();
-    remove(getRouteIdentifiers(removals));
+    if(removals != null && removals.size() > 0 ) {
+      remove(getRouteIdentifiers(removals));
+    }
   }
 
   /**
@@ -54,13 +54,8 @@ public class RoutedRpcListener implements RouteChangeListener<RpcRoutingContext,
    */
   private void announce(Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements) {
     LOG.debug("Announcing [{}]", announcements);
-    AddRoutedRpc addRpcMsg = new AddRoutedRpc(announcements, actorPath);
-    try {
-      ActorUtil.executeLocalOperation(rpcRegistry, addRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-    } catch (Exception e) {
-      // Just logging it because Akka API throws this exception
-      LOG.error(e.toString());
-    }
+    RpcRegistry.Messages.AddOrUpdateRoutes addRpcMsg = new RpcRegistry.Messages.AddOrUpdateRoutes(new ArrayList<>(announcements));
+    rpcRegistry.tell(addRpcMsg, ActorRef.noSender());
   }
 
   /**
@@ -69,13 +64,8 @@ public class RoutedRpcListener implements RouteChangeListener<RpcRoutingContext,
    */
   private void remove(Set<RpcRouter.RouteIdentifier<?, ?, ?>> removals){
     LOG.debug("Removing [{}]", removals);
-    RemoveRoutedRpc removeRpcMsg = new RemoveRoutedRpc(removals, actorPath);
-    try {
-      ActorUtil.executeLocalOperation(rpcRegistry, removeRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-    } catch (Exception e) {
-      // Just logging it because Akka API throws this exception
-      LOG.error(e.toString());
-    }
+    RpcRegistry.Messages.RemoveRoutes removeRpcMsg = new RpcRegistry.Messages.RemoveRoutes(new ArrayList<>(removals));
+    rpcRegistry.tell(removeRpcMsg, ActorRef.noSender());
   }
 
   /**
index 26e8e960e3ce46d5f9ea9b3047160134a1f2df36..611618f1f69b106d85a0959188646252fc89de60 100644 (file)
@@ -11,17 +11,17 @@ package org.opendaylight.controller.remote.rpc;
 import akka.actor.ActorRef;
 import akka.actor.Props;
 import akka.japi.Creator;
+import akka.japi.Pair;
 import org.opendaylight.controller.remote.rpc.messages.ErrorResponse;
 import org.opendaylight.controller.remote.rpc.messages.ExecuteRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.GetRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.InvokeRoutedRpc;
 import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
 import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
+import org.opendaylight.controller.remote.rpc.utils.LatestEntryRoutingLogic;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
 import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
+import org.opendaylight.controller.remote.rpc.utils.RoutingLogic;
 import org.opendaylight.controller.remote.rpc.utils.XmlUtils;
+import org.opendaylight.controller.sal.connector.api.RpcRouter;
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -29,6 +29,7 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.List;
 import java.util.concurrent.Future;
 
 /**
@@ -59,81 +60,57 @@ public class RpcBroker extends AbstractUntypedActor {
   }
   @Override
   protected void handleReceive(Object message) throws Exception {
-    if(message instanceof InvokeRoutedRpc) {
-      invokeRemoteRoutedRpc((InvokeRoutedRpc) message);
-    } else if(message instanceof InvokeRpc) {
+   if(message instanceof InvokeRpc) {
       invokeRemoteRpc((InvokeRpc) message);
     } else if(message instanceof ExecuteRpc) {
       executeRpc((ExecuteRpc) message);
     }
   }
 
-  private void invokeRemoteRoutedRpc(InvokeRoutedRpc msg) {
-    // Look up the remote actor to execute rpc
-    LOG.debug("Looking up the remote actor for route {}", msg);
-    try {
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, msg.getRpc(), msg.getIdentifier());
-      GetRoutedRpc routedRpcMsg = new GetRoutedRpc(routeId);
-      GetRoutedRpcReply rpcReply = (GetRoutedRpcReply) ActorUtil.executeLocalOperation(rpcRegistry, routedRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-
-      String remoteActorPath = rpcReply.getRoutePath();
-      if(remoteActorPath == null) {
-        LOG.debug("No remote actor found for rpc execution.");
-
-        getSender().tell(new ErrorResponse(
-          new IllegalStateException("No remote actor found for rpc execution.")), self());
-      } else {
-
-        ExecuteRpc executeMsg = new ExecuteRpc(XmlUtils.inputCompositeNodeToXml(msg.getInput(), schemaContext), msg.getRpc());
-
-        Object operationRes = ActorUtil.executeRemoteOperation(this.context().actorSelection(remoteActorPath),
-            executeMsg, ActorUtil.REMOTE_ASK_DURATION, ActorUtil.REMOTE_AWAIT_DURATION);
-
-        getSender().tell(operationRes, self());
-      }
-    } catch (Exception e) {
-        LOG.error(e.toString());
-        getSender().tell(new ErrorResponse(e), self());
-    }
-  }
-
   private void invokeRemoteRpc(InvokeRpc msg) {
     // Look up the remote actor to execute rpc
     LOG.debug("Looking up the remote actor for route {}", msg);
     try {
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, msg.getRpc(), null);
-      GetRpc rpcMsg = new GetRpc(routeId);
-      GetRpcReply rpcReply = (GetRpcReply)ActorUtil.executeLocalOperation(rpcRegistry, rpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-      String remoteActorPath = rpcReply.getRoutePath();
+      // Find router
+      RpcRouter.RouteIdentifier<?,?,?> routeId = new RouteIdentifierImpl(null, msg.getRpc(), msg.getIdentifier());
+      RpcRegistry.Messages.FindRouters rpcMsg = new RpcRegistry.Messages.FindRouters(routeId);
+      RpcRegistry.Messages.FindRoutersReply rpcReply =
+          (RpcRegistry.Messages.FindRoutersReply) ActorUtil.executeOperation(rpcRegistry, rpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
+
+      List<Pair<ActorRef, Long>> actorRefList = rpcReply.getRouterWithUpdateTime();
 
-      if(remoteActorPath == null) {
+      if(actorRefList == null || actorRefList.isEmpty()) {
         LOG.debug("No remote actor found for rpc {{}}.", msg.getRpc());
 
         getSender().tell(new ErrorResponse(
-          new IllegalStateException("No remote actor found for rpc execution of : " + msg.getRpc())), self());
+            new IllegalStateException("No remote actor found for rpc execution of : " + msg.getRpc())), self());
       } else {
+        RoutingLogic logic = new LatestEntryRoutingLogic(actorRefList);
 
         ExecuteRpc executeMsg = new ExecuteRpc(XmlUtils.inputCompositeNodeToXml(msg.getInput(), schemaContext), msg.getRpc());
-        Object operationRes = ActorUtil.executeRemoteOperation(this.context().actorSelection(remoteActorPath),
+        Object operationRes = ActorUtil.executeOperation(logic.select(),
             executeMsg, ActorUtil.REMOTE_ASK_DURATION, ActorUtil.REMOTE_AWAIT_DURATION);
 
         getSender().tell(operationRes, self());
       }
     } catch (Exception e) {
-        LOG.error(e.toString());
+        LOG.error("invokeRemoteRpc: {}", e);
         getSender().tell(new ErrorResponse(e), self());
     }
   }
 
+
+
   private void executeRpc(ExecuteRpc msg) {
     LOG.debug("Executing rpc for rpc {}", msg.getRpc());
     try {
-      Future<RpcResult<CompositeNode>> rpc = brokerSession.rpc(msg.getRpc(), XmlUtils.inputXmlToCompositeNode(msg.getRpc(), msg.getInputCompositeNode(), schemaContext));
+      Future<RpcResult<CompositeNode>> rpc = brokerSession.rpc(msg.getRpc(),
+          XmlUtils.inputXmlToCompositeNode(msg.getRpc(), msg.getInputCompositeNode(), schemaContext));
       RpcResult<CompositeNode> rpcResult = rpc != null ? rpc.get():null;
       CompositeNode result = rpcResult != null ? rpcResult.getResult() : null;
       getSender().tell(new RpcResponse(XmlUtils.outputCompositeNodeToXml(result, schemaContext)), self());
     } catch (Exception e) {
-      LOG.error(e.toString());
+      LOG.error("executeRpc: {}", e);
       getSender().tell(new ErrorResponse(e), self());
     }
   }
index f6149906692ad0e5133938068508e80364d0769e..dee98521ae9f2d56893d591b30bc30a8489d89ef 100644 (file)
@@ -10,50 +10,42 @@ package org.opendaylight.controller.remote.rpc;
 
 
 import akka.actor.ActorRef;
-import org.opendaylight.controller.remote.rpc.messages.AddRpc;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRpc;
-import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
+import org.opendaylight.controller.sal.connector.api.RpcRouter;
 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.ArrayList;
+import java.util.List;
+
 public class RpcListener implements RpcRegistrationListener{
 
   private static final Logger LOG = LoggerFactory.getLogger(RpcListener.class);
   private final ActorRef rpcRegistry;
-  private final String actorPath;
 
-  public RpcListener(ActorRef rpcRegistry, String actorPath) {
+  public RpcListener(ActorRef rpcRegistry) {
     this.rpcRegistry = rpcRegistry;
-    this.actorPath = actorPath;
   }
 
   @Override
   public void onRpcImplementationAdded(QName rpc) {
     LOG.debug("Adding registration for [{}]", rpc);
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, null);
-    AddRpc addRpcMsg = new AddRpc(routeId, actorPath);
-    try {
-      ActorUtil.executeLocalOperation(rpcRegistry, addRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-      LOG.debug("Route added [{}-{}]", routeId, this.actorPath);
-    } catch (Exception e) {
-      // Just logging it because Akka API throws this exception
-      LOG.error(e.toString());
-    }
-
+    RpcRouter.RouteIdentifier<?,?,?> routeId = new RouteIdentifierImpl(null, rpc, null);
+    List<RpcRouter.RouteIdentifier<?,?,?>> routeIds = new ArrayList<>();
+    routeIds.add(routeId);
+    RpcRegistry.Messages.AddOrUpdateRoutes addRpcMsg = new RpcRegistry.Messages.AddOrUpdateRoutes(routeIds);
+    rpcRegistry.tell(addRpcMsg, ActorRef.noSender());
   }
 
   @Override
   public void onRpcImplementationRemoved(QName rpc) {
     LOG.debug("Removing registration for [{}]", rpc);
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, null);
-    RemoveRpc removeRpcMsg = new RemoveRpc(routeId);
-    try {
-      ActorUtil.executeLocalOperation(rpcRegistry, removeRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
-    } catch (Exception e) {
-      // Just logging it because Akka API throws this exception
-      LOG.error(e.toString());
-    }
+    RpcRouter.RouteIdentifier<?,?,?> routeId = new RouteIdentifierImpl(null, rpc, null);
+    List<RpcRouter.RouteIdentifier<?,?,?>> routeIds = new ArrayList<>();
+    routeIds.add(routeId);
+    RpcRegistry.Messages.RemoveRoutes removeRpcMsg = new RpcRegistry.Messages.RemoveRoutes(routeIds);
+    rpcRegistry.tell(removeRpcMsg, ActorRef.noSender());
   }
 }
index 514a2f141daea13e5e71ec1f0f0a8acf9eadcf9d..96f24724286192131c08177943a572c45dba5a96 100644 (file)
@@ -16,8 +16,7 @@ import akka.actor.SupervisorStrategy;
 import akka.japi.Creator;
 import akka.japi.Function;
 import org.opendaylight.controller.remote.rpc.messages.UpdateSchemaContext;
-import org.opendaylight.controller.remote.rpc.registry.ClusterWrapper;
-import org.opendaylight.controller.remote.rpc.registry.RpcRegistryOld;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -38,7 +37,6 @@ public class RpcManager extends AbstractUntypedActor {
   private static final Logger LOG = LoggerFactory.getLogger(RpcManager.class);
 
   private SchemaContext schemaContext;
-  private final ClusterWrapper clusterWrapper;
   private ActorRef rpcBroker;
   private ActorRef rpcRegistry;
   private final Broker.ProviderSession brokerSession;
@@ -47,9 +45,8 @@ public class RpcManager extends AbstractUntypedActor {
   private RemoteRpcImplementation rpcImplementation;
   private final RpcProvisionRegistry rpcProvisionRegistry;
 
-  private RpcManager(ClusterWrapper clusterWrapper, SchemaContext schemaContext,
+  private RpcManager(SchemaContext schemaContext,
                      Broker.ProviderSession brokerSession, RpcProvisionRegistry rpcProvisionRegistry) {
-    this.clusterWrapper = clusterWrapper;
     this.schemaContext = schemaContext;
     this.brokerSession = brokerSession;
     this.rpcProvisionRegistry = rpcProvisionRegistry;
@@ -59,12 +56,12 @@ public class RpcManager extends AbstractUntypedActor {
   }
 
 
-  public static Props props(final ClusterWrapper clusterWrapper, final SchemaContext schemaContext,
+  public static Props props(final SchemaContext schemaContext,
                             final Broker.ProviderSession brokerSession, final RpcProvisionRegistry rpcProvisionRegistry) {
     return Props.create(new Creator<RpcManager>() {
       @Override
       public RpcManager create() throws Exception {
-        return new RpcManager(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry);
+        return new RpcManager(schemaContext, brokerSession, rpcProvisionRegistry);
       }
     });
   }
@@ -72,16 +69,19 @@ public class RpcManager extends AbstractUntypedActor {
   private void createRpcActors() {
     LOG.debug("Create rpc registry and broker actors");
 
-    rpcRegistry = getContext().actorOf(RpcRegistryOld.props(clusterWrapper), ActorConstants.RPC_REGISTRY);
+
+    rpcRegistry = getContext().actorOf(Props.create(RpcRegistry.class), ActorConstants.RPC_REGISTRY);
+
     rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), ActorConstants.RPC_BROKER);
+    RpcRegistry.Messages.SetLocalRouter localRouter = new RpcRegistry.Messages.SetLocalRouter(rpcBroker);
+    rpcRegistry.tell(localRouter, self());
   }
 
   private void startListeners() {
     LOG.debug("Registers rpc listeners");
 
-    String rpcBrokerPath = clusterWrapper.getAddress().toString() + ActorConstants.RPC_BROKER_PATH;
-    rpcListener = new RpcListener(rpcRegistry, rpcBrokerPath);
-    routeChangeListener = new RoutedRpcListener(rpcRegistry, rpcBrokerPath);
+    rpcListener = new RpcListener(rpcRegistry);
+    routeChangeListener = new RoutedRpcListener(rpcRegistry);
     rpcImplementation = new RemoteRpcImplementation(rpcBroker, schemaContext);
 
     brokerSession.addRpcRegistrationListener(rpcListener);
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRoutedRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRoutedRpc.java
deleted file mode 100644 (file)
index fd1af2b..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-
-import java.io.Serializable;
-import java.util.Set;
-
-public class AddRoutedRpc implements Serializable {
-
-  private final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
-  private final String actorPath;
-
-  public AddRoutedRpc(final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, final String actorPath) {
-    Preconditions.checkNotNull(announcements, "Route identifier should not be null");
-    Preconditions.checkNotNull(actorPath, "Actor path should not be null");
-
-    this.announcements = announcements;
-    this.actorPath = actorPath;
-  }
-
-  public Set<RpcRouter.RouteIdentifier<?, ?, ?>> getAnnouncements() {
-    return announcements;
-  }
-
-  public String getActorPath() {
-    return actorPath;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/AddRpc.java
deleted file mode 100644 (file)
index 7eaa8f0..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-
-import java.io.Serializable;
-
-public class AddRpc implements Serializable {
-
-  private final RouteIdentifierImpl routeId;
-  private final String actorPath;
-
-  public AddRpc(final RouteIdentifierImpl routeId, final String actorPath) {
-    Preconditions.checkNotNull(routeId, "Route identifier should not be null");
-    Preconditions.checkNotNull(actorPath, "Actor path should not be null");
-
-    this.routeId = routeId;
-    this.actorPath = actorPath;
-  }
-
-  public RouteIdentifierImpl getRouteId() {
-    return routeId;
-  }
-
-  public String getActorPath() {
-    return actorPath;
-  }
-}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpc.java
deleted file mode 100644 (file)
index e8d2262..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-
-import java.io.Serializable;
-
-public class GetRoutedRpc implements Serializable {
-
-  private final RouteIdentifierImpl routeId;
-
-  public GetRoutedRpc(final RouteIdentifierImpl routeId) {
-    Preconditions.checkNotNull(routeId, "route id should not be null");
-    this.routeId = routeId;
-  }
-
-  public RouteIdentifierImpl getRouteId() {
-    return routeId;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpcReply.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRoutedRpcReply.java
deleted file mode 100644 (file)
index d426662..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.opendaylight.controller.remote.rpc.messages;
-
-/*
- * 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
- */
-
-import java.io.Serializable;
-
-public class GetRoutedRpcReply implements Serializable {
-
-  private final String routePath;
-
-  public GetRoutedRpcReply(final String routePath) {
-    this.routePath = routePath;
-  }
-
-  public String getRoutePath() {
-    return routePath;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpc.java
deleted file mode 100644 (file)
index c1d4240..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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
- */
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-
-import java.io.Serializable;
-
-public class GetRpc implements Serializable {
-
-  private final RouteIdentifierImpl routeId;
-
-  public GetRpc(final RouteIdentifierImpl routeId) {
-    Preconditions.checkNotNull(routeId, "Route Id should not be null");
-    this.routeId = routeId;
-  }
-
-  public RouteIdentifierImpl getRouteId() {
-    return routeId;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpcReply.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/GetRpcReply.java
deleted file mode 100644 (file)
index aaf089d..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.opendaylight.controller.remote.rpc.messages;
-
-/*
- * 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
- */
-
-import java.io.Serializable;
-
-public class GetRpcReply implements Serializable {
-
-  private final String routePath;
-
-  public GetRpcReply(final String routePath) {
-    this.routePath = routePath;
-  }
-
-  public String getRoutePath() {
-    return routePath;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRoutedRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRoutedRpc.java
deleted file mode 100644 (file)
index fd73144..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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
- */
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
-import java.io.Serializable;
-
-public class InvokeRoutedRpc implements Serializable {
-
-  private final QName rpc;
-  private final YangInstanceIdentifier identifier;
-  private final CompositeNode input;
-
-  public InvokeRoutedRpc(final QName rpc, final YangInstanceIdentifier identifier, final CompositeNode input) {
-    Preconditions.checkNotNull(rpc, "rpc qname should not be null");
-    Preconditions.checkNotNull(identifier, "instance identifier of routed rpc should not be null");
-    Preconditions.checkNotNull(input, "rpc input should not be null");
-
-    this.rpc = rpc;
-    this.identifier = identifier;
-    this.input = input;
-  }
-
-  public QName getRpc() {
-    return rpc;
-  }
-
-  public YangInstanceIdentifier getIdentifier() {
-    return identifier;
-  }
-
-  public CompositeNode getInput() {
-    return input;
-  }
-}
index 94b7fe40244838f6115469502af862cde4daa7cc..59d09fc41b6e783491f16a2279d1124db266da09 100644 (file)
@@ -10,19 +10,22 @@ package org.opendaylight.controller.remote.rpc.messages;
 import com.google.common.base.Preconditions;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 
 import java.io.Serializable;
 
 public class InvokeRpc implements Serializable {
 
   private final QName rpc;
+  private final YangInstanceIdentifier identifier;
   private final CompositeNode input;
 
-  public InvokeRpc(final QName rpc, final CompositeNode input) {
+  public InvokeRpc(final QName rpc, final YangInstanceIdentifier identifier, final CompositeNode input) {
     Preconditions.checkNotNull(rpc, "rpc qname should not be null");
     Preconditions.checkNotNull(input, "rpc input should not be null");
 
     this.rpc = rpc;
+    this.identifier = identifier;
     this.input = input;
   }
 
@@ -30,6 +33,10 @@ public class InvokeRpc implements Serializable {
     return rpc;
   }
 
+  public YangInstanceIdentifier getIdentifier() {
+    return identifier;
+  }
+
   public CompositeNode getInput() {
     return input;
   }
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRoutedRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRoutedRpc.java
deleted file mode 100644 (file)
index b560b8c..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-
-import java.io.Serializable;
-import java.util.Set;
-
-public class RemoveRoutedRpc implements Serializable {
-
-  private final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
-  private final String actorPath;
-
-  public RemoveRoutedRpc(final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, final String actorPath) {
-    Preconditions.checkNotNull(announcements, "Route identifier should not be null");
-    Preconditions.checkNotNull(actorPath, "Actor path should not be null");
-
-    this.announcements = announcements;
-    this.actorPath = actorPath;
-  }
-
-  public Set<RpcRouter.RouteIdentifier<?, ?, ?>> getAnnouncements() {
-    return announcements;
-  }
-
-  public String getActorPath() {
-    return actorPath;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RemoveRpc.java
deleted file mode 100644 (file)
index 289334f..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-
-import java.io.Serializable;
-
-public class RemoveRpc implements Serializable {
-
-  private final RouteIdentifierImpl routeId;
-
-  public RemoveRpc(final RouteIdentifierImpl routeId) {
-    Preconditions.checkNotNull(routeId, "Route Id should not be null");
-
-    this.routeId = routeId;
-  }
-
-  public RouteIdentifierImpl getRouteId() {
-    return routeId;
-  }
-}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RoutingTableData.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RoutingTableData.java
deleted file mode 100644 (file)
index c57a258..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.messages;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-
-import java.io.Serializable;
-import java.util.LinkedHashSet;
-import java.util.Map;
-
-public class RoutingTableData implements Serializable {
-  private final Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap;
-  private final Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap;
-
-  public RoutingTableData(final Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap,
-                          final Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap) {
-    this.rpcMap = rpcMap;
-    this.routedRpcMap = routedRpcMap;
-  }
-
-  public Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> getRpcMap() {
-    return rpcMap;
-  }
-
-  public Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> getRoutedRpcMap() {
-    return routedRpcMap;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/ClusterWrapperImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/ClusterWrapperImpl.java
deleted file mode 100644 (file)
index 89603a1..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.registry;
-
-
-import akka.actor.ActorSystem;
-import akka.actor.Address;
-import akka.cluster.Cluster;
-import akka.cluster.ClusterEvent;
-
-
-public class ClusterWrapperImpl  implements ClusterWrapper{
-
-  private Cluster cluster;
-
-  public ClusterWrapperImpl(ActorSystem actorSystem) {
-    cluster = Cluster.get(actorSystem);
-  }
-
-  @Override
-  public ClusterEvent.CurrentClusterState getState() {
-    return cluster.state();
-  }
-
-  @Override
-  public Address getAddress() {
-    return cluster.selfAddress();
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOld.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOld.java
deleted file mode 100644 (file)
index 5951776..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.registry;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableSet;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class RoutingTableOld<I, R> {
-
-  private final Logger LOG = LoggerFactory.getLogger(RoutingTableOld.class);
-
-  private ConcurrentMap<I,R> globalRpcMap = new ConcurrentHashMap<>();
-  private ConcurrentMap<I, LinkedHashSet<R>> routedRpcMap = new ConcurrentHashMap<>();
-
-  public ConcurrentMap<I, R> getGlobalRpcMap() {
-    return globalRpcMap;
-  }
-
-  public ConcurrentMap<I, LinkedHashSet<R>> getRoutedRpcMap() {
-    return routedRpcMap;
-  }
-
-  public R getGlobalRoute(final I routeId) {
-    Preconditions.checkNotNull(routeId, "getGlobalRoute: routeId cannot be null!");
-    return globalRpcMap.get(routeId);
-  }
-
-  public void addGlobalRoute(final I routeId, final R route) {
-    Preconditions.checkNotNull(routeId, "addGlobalRoute: routeId cannot be null!");
-    Preconditions.checkNotNull(route, "addGlobalRoute: route cannot be null!");
-    LOG.debug("addGlobalRoute: adding  a new route with id[{}] and value [{}]", routeId, route);
-    if(globalRpcMap.putIfAbsent(routeId, route) != null) {
-      LOG.debug("A route already exist for route id [{}] ", routeId);
-    }
-  }
-
-  public void removeGlobalRoute(final I routeId) {
-    Preconditions.checkNotNull(routeId, "removeGlobalRoute: routeId cannot be null!");
-    LOG.debug("removeGlobalRoute: removing  a new route with id [{}]", routeId);
-    globalRpcMap.remove(routeId);
-  }
-
-  public Set<R> getRoutedRpc(final I routeId) {
-    Preconditions.checkNotNull(routeId, "getRoutes: routeId cannot be null!");
-    Set<R> routes = routedRpcMap.get(routeId);
-
-    if (routes == null) {
-      return Collections.emptySet();
-    }
-
-    return ImmutableSet.copyOf(routes);
-  }
-
-  public R getLastAddedRoutedRpc(final I routeId) {
-
-    Set<R> routes = getRoutedRpc(routeId);
-
-    if (routes.isEmpty()) {
-      return null;
-    }
-
-    R route = null;
-    Iterator<R> iter = routes.iterator();
-    while (iter.hasNext()) {
-      route = iter.next();
-    }
-
-    return route;
-  }
-
-  public void addRoutedRpc(final I routeId, final R route)   {
-    Preconditions.checkNotNull(routeId, "addRoute: routeId cannot be null");
-    Preconditions.checkNotNull(route, "addRoute: route cannot be null");
-    LOG.debug("addRoute: adding a route with k/v [{}/{}]", routeId, route);
-    threadSafeAdd(routeId, route);
-  }
-
-  public void addRoutedRpcs(final Set<I> routeIds, final R route) {
-    Preconditions.checkNotNull(routeIds, "addRoutes: routeIds must not be null");
-    for (I routeId : routeIds){
-      addRoutedRpc(routeId, route);
-    }
-  }
-
-  public void removeRoute(final I routeId, final R route) {
-    Preconditions.checkNotNull(routeId, "removeRoute: routeId cannot be null!");
-    Preconditions.checkNotNull(route, "removeRoute: route cannot be null!");
-
-    LinkedHashSet<R> routes = routedRpcMap.get(routeId);
-    if (routes == null) {
-      return;
-    }
-    LOG.debug("removeRoute: removing  a new route with k/v [{}/{}]", routeId, route);
-    threadSafeRemove(routeId, route);
-  }
-
-  public void removeRoutes(final Set<I> routeIds, final R route) {
-    Preconditions.checkNotNull(routeIds, "removeRoutes: routeIds must not be null");
-    for (I routeId : routeIds){
-      removeRoute(routeId, route);
-    }
-  }
-
-  /**
-   * This method guarantees that no 2 thread over write each other's changes.
-   * Just so that we dont end up in infinite loop, it tries for 100 times then throw
-   */
-  private void threadSafeAdd(final I routeId, final R route) {
-
-    for (int i=0;i<100;i++){
-
-      LinkedHashSet<R> updatedRoutes = new LinkedHashSet<>();
-      updatedRoutes.add(route);
-      LinkedHashSet<R> oldRoutes = routedRpcMap.putIfAbsent(routeId, updatedRoutes);
-      if (oldRoutes == null) {
-        return;
-      }
-
-      updatedRoutes = new LinkedHashSet<>(oldRoutes);
-      updatedRoutes.add(route);
-
-      if (routedRpcMap.replace(routeId, oldRoutes, updatedRoutes)) {
-        return;
-      }
-    }
-    //the method did not already return means it failed to add route in 100 attempts
-    throw new IllegalStateException("Failed to add route [" + routeId + "]");
-  }
-
-  /**
-   * This method guarantees that no 2 thread over write each other's changes.
-   * Just so that we dont end up in infinite loop, it tries for 100 times then throw
-   */
-  private void threadSafeRemove(final I routeId, final R route) {
-    LinkedHashSet<R> updatedRoutes = null;
-    for (int i=0;i<100;i++){
-      LinkedHashSet<R> oldRoutes = routedRpcMap.get(routeId);
-
-      // if route to be deleted is the only entry in the set then remove routeId from the cache
-      if ((oldRoutes.size() == 1) && oldRoutes.contains(route)){
-        routedRpcMap.remove(routeId);
-        return;
-      }
-
-      // if there are multiple routes for this routeId, remove the route to be deleted only from the set.
-      updatedRoutes = new LinkedHashSet<>(oldRoutes);
-      updatedRoutes.remove(route);
-      if (routedRpcMap.replace(routeId, oldRoutes, updatedRoutes)) {
-        return;
-      }
-
-    }
-    //the method did not already return means it failed to remove route in 100 attempts
-    throw new IllegalStateException("Failed to remove route [" + routeId + "]");
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOld.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOld.java
deleted file mode 100644 (file)
index 96c8802..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * 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
- */
-package org.opendaylight.controller.remote.rpc.registry;
-
-import akka.actor.ActorSelection;
-import akka.actor.Address;
-import akka.actor.Props;
-import akka.cluster.ClusterEvent;
-import akka.cluster.Member;
-import akka.japi.Creator;
-import org.opendaylight.controller.remote.rpc.AbstractUntypedActor;
-import org.opendaylight.controller.remote.rpc.ActorConstants;
-import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.AddRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.GetRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRpc;
-import org.opendaylight.controller.remote.rpc.messages.RoutingTableData;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.collection.JavaConversions;
-
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-/**
- * This Actor maintains the routing table state and sync it with other nodes in the cluster.
- *
- * A scheduler runs after an interval of time, which pick a random member from the cluster
- * and send the current state of routing table to the member.
- *
- * when a message of routing table data is received, it gets merged with the local routing table
- * to keep the latest data.
- */
-
-public class RpcRegistryOld extends AbstractUntypedActor {
-
-  private static final Logger LOG = LoggerFactory.getLogger(RpcRegistryOld.class);
-  private RoutingTableOld<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable;
-  private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
-  private final ClusterWrapper clusterWrapper;
-  private final ScheduledFuture<?> syncScheduler;
-
-  private RpcRegistryOld(ClusterWrapper clusterWrapper){
-    this.routingTable = new RoutingTableOld<>();
-    this.clusterWrapper = clusterWrapper;
-    this.syncScheduler = scheduler.scheduleAtFixedRate(new SendRoutingTable(), 10, 10, TimeUnit.SECONDS);
-  }
-
-  public static Props props(final ClusterWrapper clusterWrapper){
-    return Props.create(new Creator<RpcRegistryOld>(){
-
-      @Override
-      public RpcRegistryOld create() throws Exception {
-        return new RpcRegistryOld(clusterWrapper);
-      }
-    });
-  }
-
-  @Override
-  protected void handleReceive(Object message) throws Exception {
-    LOG.debug("Received message {}", message);
-    if(message instanceof RoutingTableData) {
-      syncRoutingTable((RoutingTableData) message);
-    } else if(message instanceof GetRoutedRpc) {
-      getRoutedRpc((GetRoutedRpc) message);
-    } else if(message instanceof GetRpc) {
-      getRpc((GetRpc) message);
-    } else if(message instanceof AddRpc) {
-      addRpc((AddRpc) message);
-    } else if(message instanceof RemoveRpc) {
-      removeRpc((RemoveRpc) message);
-    } else if(message instanceof AddRoutedRpc) {
-      addRoutedRpc((AddRoutedRpc) message);
-    } else if(message instanceof RemoveRoutedRpc) {
-      removeRoutedRpc((RemoveRoutedRpc) message);
-    }
-  }
-
-  private void getRoutedRpc(GetRoutedRpc rpcMsg){
-    LOG.debug("Get latest routed Rpc location from routing table {}", rpcMsg);
-    String remoteActorPath = routingTable.getLastAddedRoutedRpc(rpcMsg.getRouteId());
-    GetRoutedRpcReply routedRpcReply = new GetRoutedRpcReply(remoteActorPath);
-
-    getSender().tell(routedRpcReply, self());
-  }
-
-  private void getRpc(GetRpc rpcMsg) {
-    LOG.debug("Get global Rpc location from routing table {}", rpcMsg);
-    String remoteActorPath = routingTable.getGlobalRoute(rpcMsg.getRouteId());
-    GetRpcReply rpcReply = new GetRpcReply(remoteActorPath);
-
-    getSender().tell(rpcReply, self());
-  }
-
-  private void addRpc(AddRpc rpcMsg) {
-    LOG.debug("Add Rpc to routing table {}", rpcMsg);
-    routingTable.addGlobalRoute(rpcMsg.getRouteId(), rpcMsg.getActorPath());
-
-    getSender().tell("Success", self());
-  }
-
-  private void removeRpc(RemoveRpc rpcMsg) {
-    LOG.debug("Removing Rpc to routing table {}", rpcMsg);
-    routingTable.removeGlobalRoute(rpcMsg.getRouteId());
-
-    getSender().tell("Success", self());
-  }
-
-  private void addRoutedRpc(AddRoutedRpc rpcMsg) {
-    routingTable.addRoutedRpcs(rpcMsg.getAnnouncements(), rpcMsg.getActorPath());
-    getSender().tell("Success", self());
-  }
-
-  private void removeRoutedRpc(RemoveRoutedRpc rpcMsg) {
-    routingTable.removeRoutes(rpcMsg.getAnnouncements(), rpcMsg.getActorPath());
-    getSender().tell("Success", self());
-  }
-
-  private void syncRoutingTable(RoutingTableData routingTableData) {
-    LOG.debug("Syncing routing table {}", routingTableData);
-
-    Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> newRpcMap = routingTableData.getRpcMap();
-    Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIds = newRpcMap.keySet();
-    for(RpcRouter.RouteIdentifier<?, ?, ?> routeId : routeIds) {
-      routingTable.addGlobalRoute(routeId, newRpcMap.get(routeId));
-    }
-
-    Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> newRoutedRpcMap =
-        routingTableData.getRoutedRpcMap();
-    routeIds = newRoutedRpcMap.keySet();
-
-    for(RpcRouter.RouteIdentifier<?, ?, ?> routeId : routeIds) {
-      Set<String> routeAddresses = newRoutedRpcMap.get(routeId);
-      for(String routeAddress : routeAddresses) {
-        routingTable.addRoutedRpc(routeId, routeAddress);
-      }
-    }
-  }
-
-  private ActorSelection getRandomRegistryActor() {
-    ClusterEvent.CurrentClusterState clusterState = clusterWrapper.getState();
-    ActorSelection actor = null;
-    Set<Member> members = JavaConversions.asJavaSet(clusterState.members());
-    int memberSize = members.size();
-    // Don't select yourself
-    if(memberSize > 1) {
-      Address currentNodeAddress = clusterWrapper.getAddress();
-      int index = new Random().nextInt(memberSize);
-      int i = 0;
-      // keeping previous member, in case when random index member is same as current actor
-      // and current actor member is last in set
-      Member previousMember = null;
-      for(Member member : members){
-        if(i == index-1) {
-          previousMember = member;
-        }
-        if(i == index) {
-          if(!currentNodeAddress.equals(member.address())) {
-            actor = this.context().actorSelection(member.address() + ActorConstants.RPC_REGISTRY_PATH);
-            break;
-          } else if(index < memberSize-1){ // pick the next element in the set
-            index++;
-          }
-        }
-        i++;
-      }
-      if(actor == null && previousMember != null) {
-        actor = this.context().actorSelection(previousMember.address() + ActorConstants.RPC_REGISTRY_PATH);
-      }
-    }
-    return actor;
-  }
-
-  private class SendRoutingTable implements Runnable {
-
-    @Override
-    public void run() {
-      RoutingTableData routingTableData =
-          new RoutingTableData(routingTable.getGlobalRpcMap(), routingTable.getRoutedRpcMap());
-      LOG.debug("Sending routing table for sync {}", routingTableData);
-      ActorSelection actor = getRandomRegistryActor();
-      if(actor != null) {
-        actor.tell(routingTableData, self());
-      }
-    }
-  }
-}
index 8f60eabf5f98431bdb05229856b4828c20b4f0ad..b7b2216a08b0293fccc733836355ed8e4bd5767a 100644 (file)
@@ -9,7 +9,6 @@
 package org.opendaylight.controller.remote.rpc.utils;
 
 import akka.actor.ActorRef;
-import akka.actor.ActorSelection;
 import akka.util.Timeout;
 import scala.concurrent.Await;
 import scala.concurrent.Future;
@@ -36,27 +35,13 @@ public class ActorUtil {
    * @param awaitDuration
    * @return The response of the operation
    */
-  public static Object executeLocalOperation(ActorRef actor, Object message,
-                                      FiniteDuration askDuration, FiniteDuration awaitDuration) throws Exception{
+  public static Object executeOperation(ActorRef actor, Object message,
+                                        FiniteDuration askDuration, FiniteDuration awaitDuration) throws Exception{
     Future<Object> future =
         ask(actor, message, new Timeout(askDuration));
 
       return Await.result(future, awaitDuration);
   }
 
-  /**
-   * Execute an operation on a remote actor and wait for it's response
-   * @param actor
-   * @param message
-   * @param askDuration
-   * @param awaitDuration
-   * @return
-   */
-  public static Object executeRemoteOperation(ActorSelection actor, Object message,
-                                              FiniteDuration askDuration, FiniteDuration awaitDuration) throws Exception{
-    Future<Object> future =
-        ask(actor, message, new Timeout(askDuration));
-      return Await.result(future, awaitDuration);
-  }
 
 }
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogic.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogic.java
new file mode 100644 (file)
index 0000000..f01baf0
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc.utils;
+
+import akka.actor.ActorRef;
+import akka.japi.Pair;
+import com.google.common.base.Preconditions;
+
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+/**
+ * This class will return First Entry
+ */
+public class LatestEntryRoutingLogic implements RoutingLogic{
+
+  private SortedSet<Pair<ActorRef, Long>> actorRefSet;
+
+  public LatestEntryRoutingLogic(Collection<Pair<ActorRef, Long>> entries) {
+    Preconditions.checkNotNull(entries, "Entries should not be null");
+    Preconditions.checkArgument(!entries.isEmpty(), "Entries collection should not be empty");
+
+    actorRefSet = new TreeSet<>(new LatestEntryComparator());
+    actorRefSet.addAll(entries);
+  }
+
+  @Override
+  public ActorRef select() {
+    return actorRefSet.last().first();
+  }
+
+
+  private class LatestEntryComparator implements Comparator<Pair<ActorRef, Long>> {
+
+    @Override
+    public int compare(Pair<ActorRef, Long> o1, Pair<ActorRef, Long> o2) {
+      if(o1 == null && o2 == null) {
+        return 0;
+      }
+      if(o1 == null && o2 != null) {
+        return -1;
+      }
+      if(o1 != null && o2 == null) {
+        return 1;
+      }
+
+      return o1.second().compareTo(o2.second());
+
+    }
+
+  }
+}
+
+
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/RoutingLogic.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/utils/RoutingLogic.java
new file mode 100644 (file)
index 0000000..4de7194
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc.utils;
+
+import akka.actor.ActorRef;
+
+/**
+ * This Interface is added to abstract out the way rpc execution could be
+ * routed, if more than one node in cluster is capable of executing the rpc.
+ *
+ * We can pick node randomly, round robin manner or based on last updated time etc.
+ */
+
+public interface RoutingLogic {
+
+  ActorRef select();
+}
index daac89c4c8adaef39047034138a8318e639f54c8..711ae1c48b75c794bad3cb93de12e397632bcbfd 100644 (file)
@@ -53,7 +53,6 @@ odl-cluster-rpc {
 
     cluster {
       seed-nodes = ["akka.tcp://opendaylight-cluster-rpc@127.0.0.1:2551"]
-
       auto-down-unreachable-after = 10s
     }
   }
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/ActorSystemFactoryTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/ActorSystemFactoryTest.java
new file mode 100644 (file)
index 0000000..ed5fa6d
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc;
+
+
+import akka.actor.ActorSystem;
+import junit.framework.Assert;
+import org.junit.After;
+import org.junit.Test;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class ActorSystemFactoryTest {
+  ActorSystem system = null;
+
+  @Test
+  public void testActorSystemCreation(){
+    BundleContext context = mock(BundleContext.class);
+    when(context.getBundle()).thenReturn(mock(Bundle.class));
+    ActorSystemFactory.createInstance(context);
+    system = ActorSystemFactory.getInstance();
+    Assert.assertNotNull(system);
+    // Check illegal state exception
+
+    try {
+      ActorSystemFactory.createInstance(context);
+      fail("Illegal State exception should be thrown, while creating actor system second time");
+    } catch (IllegalStateException e) {
+    }
+  }
+
+  @After
+  public void cleanup() throws InterruptedException {
+    if(system != null) {
+      system.shutdown();
+    }
+  }
+
+}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RemoteRpcProviderTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RemoteRpcProviderTest.java
new file mode 100644 (file)
index 0000000..17ad237
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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
+ */
+
+
+package org.opendaylight.controller.remote.rpc;
+
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.testkit.JavaTestKit;
+import com.typesafe.config.ConfigFactory;
+import junit.framework.Assert;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import scala.concurrent.Await;
+import scala.concurrent.duration.Duration;
+
+
+import java.util.concurrent.TimeUnit;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class RemoteRpcProviderTest {
+
+  static ActorSystem system;
+
+
+  @BeforeClass
+  public static void setup() throws InterruptedException {
+    system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
+  }
+
+  @AfterClass
+  public static void teardown() {
+    JavaTestKit.shutdownActorSystem(system);
+    system = null;
+  }
+
+  @Test
+  public void testRemoteRpcProvider() throws Exception {
+    RemoteRpcProvider rpcProvider = new RemoteRpcProvider(system, mock(RpcProvisionRegistry.class));
+    Broker.ProviderSession session = mock(Broker.ProviderSession.class);
+    SchemaService schemaService = mock(SchemaService.class);
+    when(schemaService.getGlobalContext()). thenReturn(mock(SchemaContext.class));
+    when(session.getService(SchemaService.class)).thenReturn(schemaService);
+    rpcProvider.onSessionInitiated(session);
+    ActorRef actorRef = Await.result(system.actorSelection(ActorConstants.RPC_MANAGER_PATH).resolveOne(Duration.create(1, TimeUnit.SECONDS)),
+        Duration.create(2, TimeUnit.SECONDS));
+    Assert.assertTrue(actorRef.path().toString().contains(ActorConstants.RPC_MANAGER_PATH));
+  }
+
+
+
+}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RouteRpcListenerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RouteRpcListenerTest.java
new file mode 100644 (file)
index 0000000..9b6215a
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc;
+
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.testkit.JavaTestKit;
+import com.typesafe.config.ConfigFactory;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
+import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+public class RouteRpcListenerTest {
+
+  static ActorSystem system;
+
+
+  @BeforeClass
+  public static void setup() throws InterruptedException {
+    system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
+  }
+
+  @AfterClass
+  public static void teardown() {
+    JavaTestKit.shutdownActorSystem(system);
+    system = null;
+  }
+
+  @Test
+  public void testRouteAdd() throws URISyntaxException, InterruptedException {
+    new JavaTestKit(system) {
+      {
+        // Test announcements
+        JavaTestKit probeReg = new JavaTestKit(system);
+        ActorRef rpcRegistry = probeReg.getRef();
+
+        RoutedRpcListener rpcListener = new RoutedRpcListener(rpcRegistry);
+
+        QName qName = new QName(new URI("actor2"), "actor2");
+        RpcRoutingContext context = RpcRoutingContext.create(qName, qName);
+        YangInstanceIdentifier identifier = YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(qName));
+        rpcListener.onRouteChange(RoutingUtils.announcementChange(context, identifier));
+
+        probeReg.expectMsgClass(RpcRegistry.Messages.AddOrUpdateRoutes.class);
+      }};
+  }
+
+  @Test
+  public void testRouteRemove() throws URISyntaxException, InterruptedException {
+    new JavaTestKit(system) {
+      {
+        // Test announcements
+        JavaTestKit probeReg = new JavaTestKit(system);
+        ActorRef rpcRegistry = probeReg.getRef();
+
+        RoutedRpcListener rpcListener = new RoutedRpcListener(rpcRegistry);
+
+        QName qName = new QName(new URI("actor2"), "actor2");
+        RpcRoutingContext context = RpcRoutingContext.create(qName, qName);
+        YangInstanceIdentifier identifier = YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(qName));
+        rpcListener.onRouteChange(RoutingUtils.removalChange(context, identifier));
+
+        probeReg.expectMsgClass(RpcRegistry.Messages.RemoveRoutes.class);
+      }};
+  }
+}
index 55aa1d6c871d252d0a89ce1772fd078e45cac101..d9a3b6a414f1666dfa3b062cf7faa54c0baed8c0 100644 (file)
@@ -11,23 +11,21 @@ package org.opendaylight.controller.remote.rpc;
 
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
+import akka.japi.Pair;
 import akka.testkit.JavaTestKit;
 import com.google.common.util.concurrent.Futures;
+import com.typesafe.config.ConfigFactory;
 import junit.framework.Assert;
 import org.junit.AfterClass;
+import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.mockito.Mockito;
-import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.AddRpc;
 import org.opendaylight.controller.remote.rpc.messages.ErrorResponse;
-import org.opendaylight.controller.remote.rpc.messages.InvokeRoutedRpc;
 import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
 import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
-import org.opendaylight.controller.remote.rpc.registry.ClusterWrapper;
-import org.opendaylight.controller.remote.rpc.registry.RpcRegistryOld;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
 import org.opendaylight.controller.sal.common.util.Rpcs;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
@@ -35,7 +33,6 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
 import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
@@ -43,8 +40,7 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
+import java.util.List;
 import java.util.concurrent.Future;
 
 import static org.mockito.Mockito.mock;
@@ -52,31 +48,50 @@ import static org.mockito.Mockito.when;
 
 public class RpcBrokerTest {
 
-  static ActorSystem system;
+  static ActorSystem node1;
+  static ActorSystem node2;
+  private ActorRef rpcBroker1;
+  private JavaTestKit probeReg1;
+  private ActorRef rpcBroker2;
+  private JavaTestKit probeReg2;
+  private Broker.ProviderSession brokerSession;
 
 
   @BeforeClass
-  public static void setup() {
-    system = ActorSystem.create();
+  public static void setup() throws InterruptedException {
+    node1 = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("memberA"));
+    node2 = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("memberB"));
   }
 
   @AfterClass
   public static void teardown() {
-    JavaTestKit.shutdownActorSystem(system);
-    system = null;
+    JavaTestKit.shutdownActorSystem(node1);
+    JavaTestKit.shutdownActorSystem(node2);
+    node1 = null;
+    node2 = null;
   }
 
+  @Before
+  public void createActor() {
+    brokerSession = Mockito.mock(Broker.ProviderSession.class);
+    SchemaContext schemaContext = mock(SchemaContext.class);
+    probeReg1 = new JavaTestKit(node1);
+    rpcBroker1 = node1.actorOf(RpcBroker.props(brokerSession, probeReg1.getRef(), schemaContext));
+    probeReg2 = new JavaTestKit(node2);
+    rpcBroker2 = node2.actorOf(RpcBroker.props(brokerSession, probeReg2.getRef(), schemaContext));
+
+  }
   @Test
-  public void testInvokeRpcError() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(Mockito.mock(ClusterWrapper.class)));
-      Broker.ProviderSession brokerSession = Mockito.mock(Broker.ProviderSession.class);
-      SchemaContext schemaContext = mock(SchemaContext.class);
-      ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
+  public void testInvokeRpcError() throws Exception {
+    new JavaTestKit(node1) {{
       QName rpc = new QName(new URI("noactor1"), "noactor1");
       CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "no child"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-      InvokeRpc invokeMsg = new InvokeRpc(rpc, input);
-      rpcBroker.tell(invokeMsg, getRef());
+
+
+      InvokeRpc invokeMsg = new InvokeRpc(rpc, null, input);
+      rpcBroker1.tell(invokeMsg, getRef());
+      probeReg1.expectMsgClass(RpcRegistry.Messages.FindRouters.class);
+      probeReg1.reply(new RpcRegistry.Messages.FindRoutersReply(new ArrayList<Pair<ActorRef, Long>>()));
 
       Boolean getMsg = new ExpectMsg<Boolean>("ErrorResponse") {
         protected Boolean match(Object in) {
@@ -90,114 +105,36 @@ public class RpcBrokerTest {
       }.get(); // this extracts the received message
 
       Assert.assertTrue(getMsg);
+
     }};
   }
 
+
   /**
    * This test method invokes and executes the remote rpc
    */
 
   @Test
   public void testInvokeRpc() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(mock(ClusterWrapper.class)));
-      Broker.ProviderSession brokerSession = mock(Broker.ProviderSession.class);
-      SchemaContext schemaContext = mock(SchemaContext.class);
-      ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
-      ActorRef rpcBrokerRemote = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "actor1");
-      // Add RPC in table
-      QName rpc = new QName(new URI("actor1"), "actor1");
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, null);
-      final String route = rpcBrokerRemote.path().toString();
-      AddRpc rpcMsg = new AddRpc(routeId, route);
-      rpcRegistry.tell(rpcMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
-
+    new JavaTestKit(node1) {{
+      QName rpc = new QName(new URI("noactor1"), "noactor1");
       // invoke rpc
       CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "child1"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-      CompositeNode invokeRpcResult = mock(CompositeNode.class);
-      Collection<RpcError> errors = new ArrayList<>();
-      RpcResult<CompositeNode> result = Rpcs.getRpcResult(true, invokeRpcResult, errors);
-      Future<RpcResult<CompositeNode>> rpcResult = Futures.immediateFuture(result);
-      when(brokerSession.rpc(rpc, input)).thenReturn(rpcResult);
-      InvokeRpc invokeMsg = new InvokeRpc(rpc, input);
-      rpcBroker.tell(invokeMsg, getRef());
-
-      //verify response msg
-      Boolean getMsg = new ExpectMsg<Boolean>("RpcResponse") {
-        protected Boolean match(Object in) {
-          if (in instanceof RpcResponse) {
-            return true;
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get(); // this extracts the received message
-
-      Assert.assertTrue(getMsg);
-    }};
-  }
-
-  @Test
-  public void testInvokeRoutedRpcError() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(Mockito.mock(ClusterWrapper.class)));
-      Broker.ProviderSession brokerSession = Mockito.mock(Broker.ProviderSession.class);
-      SchemaContext schemaContext = mock(SchemaContext.class);
-      ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
-      QName rpc = new QName(new URI("actor1"), "actor1");
-      CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "child1"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-      InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(rpc)), input);
-      rpcBroker.tell(invokeMsg, getRef());
+      InvokeRpc invokeMsg = new InvokeRpc(rpc, null, input);
+      rpcBroker1.tell(invokeMsg, getRef());
 
-      Boolean getMsg = new ExpectMsg<Boolean>("ErrorResponse") {
-        protected Boolean match(Object in) {
-          if (in instanceof ErrorResponse) {
-            ErrorResponse reply = (ErrorResponse)in;
-            return "No remote actor found for rpc execution.".equals(reply.getException().getMessage());
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get(); // this extracts the received message
-
-      Assert.assertTrue(getMsg);
-    }};
-  }
+      probeReg1.expectMsgClass(RpcRegistry.Messages.FindRouters.class);
+      List<Pair<ActorRef, Long>> routerList = new ArrayList<Pair<ActorRef, Long>>();
 
-  /**
-   * This test method invokes and executes the remote routed rpc
-   */
+      routerList.add(new Pair<ActorRef, Long>(rpcBroker2, 200L));
 
-  @Test
-  public void testInvokeRoutedRpc() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(mock(ClusterWrapper.class)));
-      Broker.ProviderSession brokerSession = mock(Broker.ProviderSession.class);
-      SchemaContext schemaContext = mock(SchemaContext.class);
-      ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
-      ActorRef rpcBrokerRemote = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "actor2");
-      // Add Routed RPC in table
-      QName rpc = new QName(new URI("actor2"), "actor2");
-      YangInstanceIdentifier identifier = YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(rpc));
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, identifier);
-      final String route = rpcBrokerRemote.path().toString();
-      Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIds = new HashSet<>();
-      routeIds.add(routeId);
-
-      AddRoutedRpc rpcMsg = new AddRoutedRpc(routeIds, route);
-      rpcRegistry.tell(rpcMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
+      probeReg1.reply(new RpcRegistry.Messages.FindRoutersReply(routerList));
 
-      // invoke rpc
-      CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "child1"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
       CompositeNode invokeRpcResult = mock(CompositeNode.class);
       Collection<RpcError> errors = new ArrayList<>();
       RpcResult<CompositeNode> result = Rpcs.getRpcResult(true, invokeRpcResult, errors);
       Future<RpcResult<CompositeNode>> rpcResult = Futures.immediateFuture(result);
       when(brokerSession.rpc(rpc, input)).thenReturn(rpcResult);
-      InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, identifier, input);
-      rpcBroker.tell(invokeMsg, getRef());
 
       //verify response msg
       Boolean getMsg = new ExpectMsg<Boolean>("RpcResponse") {
@@ -213,5 +150,4 @@ public class RpcBrokerTest {
       Assert.assertTrue(getMsg);
     }};
   }
-
 }
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RpcListenerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/RpcListenerTest.java
new file mode 100644 (file)
index 0000000..7b5a968
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.testkit.JavaTestKit;
+import com.typesafe.config.ConfigFactory;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
+import org.opendaylight.yangtools.yang.common.QName;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+public class RpcListenerTest {
+
+  static ActorSystem system;
+
+
+  @BeforeClass
+  public static void setup() throws InterruptedException {
+    system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
+  }
+
+  @AfterClass
+  public static void teardown() {
+    JavaTestKit.shutdownActorSystem(system);
+    system = null;
+  }
+
+  @Test
+  public void testRpcAdd() throws URISyntaxException {
+    new JavaTestKit(system) {
+      {
+        JavaTestKit probeReg = new JavaTestKit(system);
+        ActorRef rpcRegistry = probeReg.getRef();
+
+        RpcListener rpcListener = new RpcListener(rpcRegistry);
+
+        QName qName = new QName(new URI("actor2"), "actor2");
+
+        rpcListener.onRpcImplementationAdded(qName);
+        probeReg.expectMsgClass(RpcRegistry.Messages.AddOrUpdateRoutes.class);
+      }};
+
+  }
+
+  @Test
+  public void testRpcRemove() throws URISyntaxException {
+    new JavaTestKit(system) {
+      {
+        JavaTestKit probeReg = new JavaTestKit(system);
+        ActorRef rpcRegistry = probeReg.getRef();
+
+        RpcListener rpcListener = new RpcListener(rpcRegistry);
+
+        QName qName = new QName(new URI("actor2"), "actor2");
+
+        rpcListener.onRpcImplementationRemoved(qName);
+        probeReg.expectMsgClass(RpcRegistry.Messages.RemoveRoutes.class);
+      }};
+
+  }
+}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOldTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RoutingTableOldTest.java
deleted file mode 100644 (file)
index 524a912..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.registry;
-
-import junit.framework.Assert;
-import org.junit.Test;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.yangtools.yang.common.QName;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashSet;
-import java.util.Set;
-
-public class RoutingTableOldTest {
-
-  private RoutingTableOld<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable =
-      new RoutingTableOld<>();
-
-  @Test
-  public void addGlobalRouteNullRouteIdTest() {
-    try {
-      routingTable.addGlobalRoute(null, null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("addGlobalRoute: routeId cannot be null!", e.getMessage());
-    }
-  }
-
-  @Test
-  public void addGlobalRouteNullRouteTest() {
-    try {
-      QName type = new QName(new URI("actor1"), "actor1");
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-      routingTable.addGlobalRoute(routeId, null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("addGlobalRoute: route cannot be null!", e.getMessage());
-    }
-  }
-
-  @Test
-  public void getGlobalRouteNullTest() {
-    try {
-      routingTable.getGlobalRoute(null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("getGlobalRoute: routeId cannot be null!", e.getMessage());
-    }
-  }
-
-  @Test
-  public void getGlobalRouteTest() throws URISyntaxException {
-    QName type = new QName(new URI("actor1"), "actor1");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-    String route = "actor1";
-
-    routingTable.addGlobalRoute(routeId, route);
-
-    String returnedRoute = routingTable.getGlobalRoute(routeId);
-
-    Assert.assertEquals(route, returnedRoute);
-
-  }
-
-  @Test
-  public void removeGlobalRouteTest() throws URISyntaxException {
-    QName type = new QName(new URI("actorRemove"), "actorRemove");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-    String route = "actorRemove";
-
-    routingTable.addGlobalRoute(routeId, route);
-
-    String returnedRoute = routingTable.getGlobalRoute(routeId);
-
-    Assert.assertEquals(route, returnedRoute);
-
-    routingTable.removeGlobalRoute(routeId);
-
-    String deletedRoute = routingTable.getGlobalRoute(routeId);
-
-    Assert.assertNull(deletedRoute);
-  }
-
-  @Test
-  public void addRoutedRpcNullRouteIdTest() {
-    try {
-      routingTable.addRoutedRpc(null, null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("addRoute: routeId cannot be null", e.getMessage());
-    }
-  }
-
-  @Test
-  public void addRoutedRpcNullRouteTest() {
-    try {
-      QName type = new QName(new URI("actor1"), "actor1");
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-
-      routingTable.addRoutedRpc(routeId, null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("addRoute: route cannot be null", e.getMessage());
-    }
-  }
-
-  @Test
-  public void getRoutedRpcNullTest() {
-    try {
-      routingTable.getRoutedRpc(null);
-
-      Assert.fail("Null pointer exception was not thrown.");
-    } catch (Exception e) {
-      Assert.assertEquals(NullPointerException.class.getName(), e.getClass().getName());
-      Assert.assertEquals("getRoutes: routeId cannot be null!", e.getMessage());
-    }
-  }
-
-  @Test
-  public void getRoutedRpcTest() throws URISyntaxException {
-    QName type = new QName(new URI("actor1"), "actor1");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-    String route = "actor1";
-
-    routingTable.addRoutedRpc(routeId, route);
-
-    Set<String> routes = routingTable.getRoutedRpc(routeId);
-
-    Assert.assertEquals(1, routes.size());
-    Assert.assertTrue(routes.contains(route));
-
-  }
-
-  @Test
-  public void getLastRoutedRpcTest() throws URISyntaxException {
-    QName type = new QName(new URI("first1"), "first1");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-    String route = "first1";
-
-    routingTable.addRoutedRpc(routeId, route);
-
-    String route2 = "second1";
-    routingTable.addRoutedRpc(routeId, route2);
-
-    String latest = routingTable.getLastAddedRoutedRpc(routeId);
-    Assert.assertEquals(route2, latest);
-
-  }
-
-  @Test
-  public void removeRoutedRpcTest() throws URISyntaxException {
-    QName type = new QName(new URI("remove"), "remove");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-    String route = "remove";
-    routingTable.addRoutedRpc(routeId, route);
-
-    String latest = routingTable.getLastAddedRoutedRpc(routeId);
-    Assert.assertEquals(route, latest);
-
-    routingTable.removeRoute(routeId, route);
-    String removed = routingTable.getLastAddedRoutedRpc(routeId);
-    Assert.assertNull(removed);
-  }
-
-  @Test
-  public void removeRoutedRpcsTest() throws URISyntaxException {
-    QName type = new QName(new URI("remove1"), "remove1");
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-
-    QName type2 = new QName(new URI("remove2"), "remove2");
-    RouteIdentifierImpl routeId2 = new RouteIdentifierImpl(null, type2, null);
-
-    Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIds = new HashSet<>();
-    routeIds.add(routeId);
-    routeIds.add(routeId2);
-    String route = "remove1";
-
-    routingTable.addRoutedRpcs(routeIds, route);
-    String latest1 = routingTable.getLastAddedRoutedRpc(routeId);
-    Assert.assertEquals(route, latest1);
-
-    String latest2 = routingTable.getLastAddedRoutedRpc(routeId2);
-    Assert.assertEquals(route, latest2);
-
-    routingTable.removeRoutes(routeIds, route);
-    String removed1 = routingTable.getLastAddedRoutedRpc(routeId);
-    Assert.assertNull(removed1);
-
-    String removed2 = routingTable.getLastAddedRoutedRpc(routeId2);
-    Assert.assertNull(removed2);
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOldTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryOldTest.java
deleted file mode 100644 (file)
index 0f711b4..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 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
- */
-
-package org.opendaylight.controller.remote.rpc.registry;
-
-import akka.actor.ActorRef;
-import akka.actor.ActorSystem;
-import akka.testkit.JavaTestKit;
-import junit.framework.Assert;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
-import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.AddRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.GetRpc;
-import org.opendaylight.controller.remote.rpc.messages.GetRpcReply;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRoutedRpc;
-import org.opendaylight.controller.remote.rpc.messages.RemoveRpc;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.yangtools.yang.common.QName;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashSet;
-import java.util.Set;
-
-public class RpcRegistryOldTest {
-
-  static ActorSystem system;
-
-
-  @BeforeClass
-  public static void setup() {
-    system = ActorSystem.create();
-  }
-
-  @AfterClass
-  public static void teardown() {
-    JavaTestKit.shutdownActorSystem(system);
-    system = null;
-  }
-
-  /**
-   This test add, read and remove an entry in global rpc
-   */
-  @Test
-  public void testGlobalRpc() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(Mockito.mock(ClusterWrapper.class)));
-      QName type = new QName(new URI("actor1"), "actor1");
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-      final String route = "actor1";
-
-      AddRpc rpcMsg = new AddRpc(routeId, route);
-      rpcRegistry.tell(rpcMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
-
-      GetRpc getRpc = new GetRpc(routeId);
-      rpcRegistry.tell(getRpc, getRef());
-
-      Boolean getMsg = new ExpectMsg<Boolean>("GetRpcReply") {
-        protected Boolean match(Object in) {
-          if (in instanceof GetRpcReply) {
-            GetRpcReply reply = (GetRpcReply)in;
-            return route.equals(reply.getRoutePath());
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get(); // this extracts the received message
-
-      Assert.assertTrue(getMsg);
-
-      RemoveRpc removeMsg = new RemoveRpc(routeId);
-      rpcRegistry.tell(removeMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
-
-      rpcRegistry.tell(getRpc, getRef());
-
-      Boolean getNullMsg = new ExpectMsg<Boolean>("GetRpcReply") {
-        protected Boolean match(Object in) {
-          if (in instanceof GetRpcReply) {
-            GetRpcReply reply = (GetRpcReply)in;
-            return reply.getRoutePath() == null;
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get();
-      Assert.assertTrue(getNullMsg);
-    }};
-
-  }
-
-  /**
-   This test add, read and remove an entry in routed rpc
-   */
-  @Test
-  public void testRoutedRpc() throws URISyntaxException {
-    new JavaTestKit(system) {{
-      ActorRef rpcRegistry = system.actorOf(RpcRegistryOld.props(Mockito.mock(ClusterWrapper.class)));
-      QName type = new QName(new URI("actor1"), "actor1");
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
-      final String route = "actor1";
-
-      Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIds = new HashSet<>();
-      routeIds.add(routeId);
-
-      AddRoutedRpc rpcMsg = new AddRoutedRpc(routeIds, route);
-      rpcRegistry.tell(rpcMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
-
-      GetRoutedRpc getRpc = new GetRoutedRpc(routeId);
-      rpcRegistry.tell(getRpc, getRef());
-
-      Boolean getMsg = new ExpectMsg<Boolean>("GetRoutedRpcReply") {
-        protected Boolean match(Object in) {
-          if (in instanceof GetRoutedRpcReply) {
-            GetRoutedRpcReply reply = (GetRoutedRpcReply)in;
-            return route.equals(reply.getRoutePath());
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get(); // this extracts the received message
-
-      Assert.assertTrue(getMsg);
-
-      RemoveRoutedRpc removeMsg = new RemoveRoutedRpc(routeIds, route);
-      rpcRegistry.tell(removeMsg, getRef());
-      expectMsgEquals(duration("2 second"), "Success");
-
-      rpcRegistry.tell(getRpc, getRef());
-
-      Boolean getNullMsg = new ExpectMsg<Boolean>("GetRoutedRpcReply") {
-        protected Boolean match(Object in) {
-          if (in instanceof GetRoutedRpcReply) {
-            GetRoutedRpcReply reply = (GetRoutedRpcReply)in;
-            return reply.getRoutePath() == null;
-          } else {
-            throw noMatch();
-          }
-        }
-      }.get();
-      Assert.assertTrue(getNullMsg);
-    }};
-
-  }
-
-}
index 7e87da0f99216c706c6935164713adb4e0c58265..fd6664af9e618872eb6f8a656cc7beddb68aa0bc 100644 (file)
@@ -34,7 +34,7 @@ public class BucketStoreTest {
     @BeforeClass
     public static void setup() {
 
-        system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("unit-test"));
+        system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
         system.actorOf(Props.create(TerminationMonitor.class), "termination-monitor");
 
         store = createStore();
index f076c136feb80d0752777988efb711766086721a..bb60ed6eec05c4151dce935d2fc198d82c98577f 100644 (file)
@@ -45,8 +45,7 @@ public class GossiperTest {
 
     @BeforeClass
     public static void setup() throws InterruptedException {
-        Thread.sleep(1000);//give some time for previous test to stop the system. Netty port conflict arises otherwise.
-        system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("unit-test"));
+        system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
         system.actorOf(Props.create(TerminationMonitor.class), "termination-monitor");
 
         gossiper = createGossiper();
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java
new file mode 100644 (file)
index 0000000..b21f0f0
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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
+ */
+
+package org.opendaylight.controller.remote.rpc.utils;
+
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.japi.Pair;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestProbe;
+import com.typesafe.config.ConfigFactory;
+import junit.framework.Assert;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+public class LatestEntryRoutingLogicTest {
+
+  static ActorSystem system;
+
+  @BeforeClass
+  public static void setup() throws InterruptedException {
+    system = ActorSystem.create("opendaylight-rpc", ConfigFactory.load().getConfig("odl-cluster"));
+  }
+
+  @AfterClass
+  public static void teardown() {
+    JavaTestKit.shutdownActorSystem(system);
+    system = null;
+  }
+
+  @Test
+  public void testRoutingLogic() {
+    List<Pair<ActorRef, Long>> pairList = new ArrayList<>();
+    TestProbe probe1 = new TestProbe(system);
+    TestProbe probe2 = new TestProbe(system);
+    TestProbe probe3 = new TestProbe(system);
+    ActorRef actor1 = probe1.ref();
+    ActorRef actor2 = probe2.ref();
+    ActorRef actor3 = probe3.ref();
+    pairList.add(new Pair<ActorRef, Long>(actor1, 1000L));
+    pairList.add(new Pair<ActorRef, Long>(actor2, 3000L));
+    pairList.add(new Pair<ActorRef, Long>(actor3, 2000L));
+    RoutingLogic logic = new LatestEntryRoutingLogic(pairList);
+    Assert.assertTrue(logic.select().equals(actor2));
+  }
+}
index 459eb78903b6dc09b0739b49198a71d71f05c2f2..61fab7e0fefccfd26909a8eb81e2af041d624662 100644 (file)
@@ -18,12 +18,12 @@ odl-cluster{
       log-remote-lifecycle-events = off
       netty.tcp {
         hostname = "127.0.0.1"
-        port = 2551
+        port = 2550
       }
     }
 
     cluster {
-      seed-nodes = ["akka.tcp://opendaylight-rpc@127.0.0.1:2551"]
+      seed-nodes = ["akka.tcp://opendaylight-rpc@127.0.0.1:2550"]
 
       auto-down-unreachable-after = 10s
     }
index ed20bd01a5047e4d746858ff4adde4fe7de0c701..544a144987a68a77f9ec14e3c22d77cf1962fae8 100644 (file)
@@ -62,7 +62,7 @@ public class RestconfError {
         RESOURCE_DENIED("resource-denied", 409 /* Conflict */),
         ROLLBACK_FAILED("rollback-failed", 500 /* INTERNAL_SERVER_ERROR */),
         DATA_EXISTS("data-exists", 409 /* Conflict */),
-        DATA_MISSING("data-missing", 409 /* Conflict */),
+        DATA_MISSING("data-missing", 404 /* Resource Not Found */),
         OPERATION_NOT_SUPPORTED("operation-not-supported", 501 /* Not Implemented */),
         OPERATION_FAILED("operation-failed", 500 /* INTERNAL_SERVER_ERROR */),
         PARTIAL_OPERATION("partial-operation", 500 /* INTERNAL_SERVER_ERROR */),
index b8c0270a61407a8358a741abe2515bc83395ef60..2747b9e264c9391f7e5cf9b8f262bb4f33859c09 100644 (file)
@@ -374,7 +374,7 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
     public void testToJsonResponseWithDataMissingErrorTag() throws Exception {
 
         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
-                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
+                Status.NOT_FOUND, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
@@ -594,7 +594,7 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
     public void testToXMLResponseWithDataMissingErrorTag() throws Exception {
 
         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
-                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
+                Status.NOT_FOUND, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
index 18311104a41f9761dd5bede15965df9625ea061b..010572de968736fabbda746d3ff5c8b101a5c433 100644 (file)
@@ -90,7 +90,7 @@ public class RestconfErrorTest {
         lookUpMap.put("resource-denied", 409);
         lookUpMap.put("rollback-failed", 500);
         lookUpMap.put("data-exists", 409);
-        lookUpMap.put("data-missing", 409);
+        lookUpMap.put("data-missing", 404);
         lookUpMap.put("operation-not-supported", 501);
         lookUpMap.put("operation-failed", 500);
         lookUpMap.put("partial-operation", 500);
index 701911d9a2c307c03ecd48c75bfcd4099ba2490f..e4490eaa3cc2ea9ac2683ff36f6d48787ddded99 100644 (file)
@@ -31,12 +31,12 @@ final class NodeConnectorStatsTracker extends AbstractStatsTracker<NodeConnector
     }
 
     @Override
-    protected void cleanupSingleStat(DataModificationTransaction trans, NodeConnectorStatisticsAndPortNumberMap item) {
+    protected void cleanupSingleStat(final DataModificationTransaction trans, final NodeConnectorStatisticsAndPortNumberMap item) {
         // TODO Auto-generated method stub
     }
 
     @Override
-    protected NodeConnectorStatisticsAndPortNumberMap updateSingleStat(DataModificationTransaction trans, NodeConnectorStatisticsAndPortNumberMap item) {
+    protected NodeConnectorStatisticsAndPortNumberMap updateSingleStat(final DataModificationTransaction trans, final NodeConnectorStatisticsAndPortNumberMap item) {
         FlowCapableNodeConnectorStatisticsBuilder statisticsBuilder
                                         = new FlowCapableNodeConnectorStatisticsBuilder();
         statisticsBuilder.setBytes(item.getBytes());
@@ -57,16 +57,17 @@ final class NodeConnectorStatsTracker extends AbstractStatsTracker<NodeConnector
 
         statisticsDataBuilder.setFlowCapableNodeConnectorStatistics(statisticsBuilder.build());
 
-        InstanceIdentifier<NodeConnector> nodeConnectorRef = getNodeIdentifierBuilder()
-                .child(NodeConnector.class, new NodeConnectorKey(item.getNodeConnectorId())).build();
+        final NodeConnectorKey key = new NodeConnectorKey(item.getNodeConnectorId());
+        final InstanceIdentifier<NodeConnector> nodeConnectorRef = getNodeIdentifier().child(NodeConnector.class, key);
 
         // FIXME: can we bypass this read?
         NodeConnector nodeConnector = (NodeConnector)trans.readOperationalData(nodeConnectorRef);
         if(nodeConnector != null){
             final FlowCapableNodeConnectorStatisticsData stats = statisticsDataBuilder.build();
             logger.debug("Augmenting port statistics {} to port {}",stats,nodeConnectorRef.toString());
-            NodeConnectorBuilder nodeConnectorBuilder = new NodeConnectorBuilder();
-            nodeConnectorBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, stats);
+            NodeConnectorBuilder nodeConnectorBuilder = new NodeConnectorBuilder()
+                .setKey(key).setId(item.getNodeConnectorId())
+                .addAugmentation(FlowCapableNodeConnectorStatisticsData.class, stats);
             trans.putOperationalData(nodeConnectorRef, nodeConnectorBuilder.build());
         }
 
index 0a3b9f6a6b7c53c193cd3fd523504d4e729df180..556047091c1a779f6af251d9da0e00c50f6c6536 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.md.controller.topology.manager;
 
 import java.util.concurrent.ExecutionException;
+
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -44,16 +45,15 @@ public class FlowCapableTopologyProvider extends AbstractBindingAwareProvider im
         final String name = "flow:1";
         final TopologyKey key = new TopologyKey(new TopologyId(name));
         final InstanceIdentifier<Topology> path = InstanceIdentifier
-                .builder(NetworkTopology.class)
-                .child(Topology.class, key)
-                .build();
+                .create(NetworkTopology.class)
+                .child(Topology.class, key);
 
         final OperationProcessor processor = new OperationProcessor(dataBroker);
         final FlowCapableTopologyExporter listener = new FlowCapableTopologyExporter(processor, path);
         this.listenerRegistration = notificationService.registerNotificationListener(listener);
 
         final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
-        tx.put(LogicalDatastoreType.OPERATIONAL, path, new TopologyBuilder().setKey(key).build());
+        tx.put(LogicalDatastoreType.OPERATIONAL, path, new TopologyBuilder().setKey(key).build(), true);
         try {
             tx.submit().get();
         } catch (InterruptedException | ExecutionException e) {