Merge "xsql should pull junit directly"
authorTony Tkacik <ttkacik@cisco.com>
Mon, 23 Feb 2015 10:45:09 +0000 (10:45 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 23 Feb 2015 10:45:09 +0000 (10:45 +0000)
73 files changed:
opendaylight/commons/opendaylight/pom.xml
opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java
opendaylight/md-sal/messagebus-impl/pom.xml
opendaylight/md-sal/messagebus-impl/src/main/java/org/opendaylight/controller/messagebus/app/impl/Topic.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/ForwardMessageToBehaviorActor.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMBrokerPerformanceTest.java
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMBrokerTest.java
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMTransactionChainTest.java
opendaylight/md-sal/sal-dummy-distributed-datastore/pom.xml
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/InMemoryDataStoreTest.java
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaUpdateForTransactionTest.java
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/TestDCLExecutorService.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceFactoryImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreService.java
opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/NetconfMappingTest.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusherImpl.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java
opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java
opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/MockedBundleContext.java
opendaylight/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/controller/netconf/mdsal/connector/MdsalNetconfOperationService.java
opendaylight/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/controller/netconf/mdsal/connector/MdsalNetconfOperationServiceFactory.java
opendaylight/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/controller/netconf/mdsal/connector/ops/get/AbstractGet.java
opendaylight/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/controller/netconf/mdsal/connector/ops/get/Get.java
opendaylight/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/controller/netconf/mdsal/connector/ops/get/GetConfig.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/Capability.java [moved from opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/Capability.java with 93% similarity]
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/monitoring/CapabilityListener.java [new file with mode: 0644]
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/monitoring/NetconfMonitoringService.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/monitoring/SessionListener.java [moved from opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/SessionMonitoringService.java with 59% similarity]
opendaylight/netconf/netconf-api/src/main/yang/netconf-northbound.yang
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/config/yang/config/netconf/northbound/impl/NetconfServerDispatcherModule.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/CapabilityProviderImpl.java [deleted file]
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionListener.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionListenerFactory.java [deleted file]
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiatorFactory.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/CapabilityProvider.java [deleted file]
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCommit.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/AggregatedNetconfOperationServiceFactory.java [new file with mode: 0644]
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivator.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfMonitoringServiceImpl.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationRouterImpl.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryListenerImpl.java [deleted file]
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceSnapshotImpl.java [deleted file]
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/ConcurrentClientsTest.java
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfDispatcherImplTest.java
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfMonitoringServiceImplTest.java
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCommitTest.java
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivatorTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITMonitoringTest.java
opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationProvider.java [deleted file]
opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationService.java
opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationServiceFactory.java
opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationServiceSnapshot.java [deleted file]
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/GetSchema.java [moved from opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchema.java with 75% similarity]
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringOperationService.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java
opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetSchemaTest.java [moved from opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchemaTest.java with 82% similarity]
opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringOperationServiceTest.java
opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializerTest.java
opendaylight/netconf/netconf-notifications-impl/src/main/java/org/opendaylight/controller/netconf/notifications/impl/osgi/Activator.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/FakeModuleBuilderCapability.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/ModuleBuilderCapability.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/NetconfDeviceSimulator.java

index 9a88e610072036b74e986947e73e19eb8ff0a10b..43ac4ae91c4a446cea6128fab4c14d1e0593a44f 100644 (file)
@@ -15,7 +15,7 @@
 
   <properties>
 
-    <akka.version>2.3.4</akka.version>
+    <akka.version>2.3.9</akka.version>
     <appauth.version>0.5.0-SNAPSHOT</appauth.version>
     <archetype-app-northbound>0.1.0-SNAPSHOT</archetype-app-northbound>
     <arphandler.version>0.6.0-SNAPSHOT</arphandler.version>
     <jmxGeneratorPath>src/main/yang-gen-config</jmxGeneratorPath>
     <jolokia-bridge.version>0.1.0-SNAPSHOT</jolokia-bridge.version>
     <jolokia.version>1.1.4</jolokia.version>
-    <jsr305.api.version>2.0.1</jsr305.api.version>
     <jsr311.api.version>1.1.1</jsr311.api.version>
     <jsr311.v2.api.version>2.0</jsr311.v2.api.version>
     <karaf.branding.version>1.1.0-SNAPSHOT</karaf.branding.version>
         <artifactId>java-concurrent-hash-trie-map</artifactId>
         <version>${ctrie.version}</version>
       </dependency>
-      <dependency>
-        <groupId>com.google.code.findbugs</groupId>
-        <artifactId>jsr305</artifactId>
-        <version>${jsr305.api.version}</version>
-      </dependency>
       <dependency>
         <groupId>com.google.code.gson</groupId>
         <artifactId>gson</artifactId>
index 19e875f9b1805f851322e82ebb565752c9d710cc..00454d8acf14507a518e63b5d71b79020ce89bfd 100644 (file)
@@ -48,9 +48,9 @@ import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Meth
 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
 import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
 import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
 
 public class TemplateFactory {
 
@@ -59,7 +59,7 @@ public class TemplateFactory {
      * bean as value that should be persisted from this instance.
      */
     public static Map<String, FtlTemplate> getTOAndMXInterfaceFtlFiles(
-            RuntimeBeanEntry entry) {
+            final RuntimeBeanEntry entry) {
         Map<String, FtlTemplate> result = new HashMap<>();
         { // create GeneralInterfaceFtlFile for runtime MXBean. Attributes will
           // be transformed to getter methods
@@ -109,7 +109,7 @@ public class TemplateFactory {
     }
 
     // FIXME: put into Type.toString
-    static String serializeType(Type type, boolean addWildcards) {
+    static String serializeType(final Type type, final boolean addWildcards) {
         if (type instanceof ParameterizedType){
             ParameterizedType parameterizedType = (ParameterizedType) type;
             StringBuilder sb = new StringBuilder();
@@ -131,11 +131,11 @@ public class TemplateFactory {
         }
     }
 
-    static String serializeType(Type type) {
+    static String serializeType(final Type type) {
         return serializeType(type, false);
     }
 
-    private static String getReturnType(AttributeIfc attributeIfc) {
+    private static String getReturnType(final AttributeIfc attributeIfc) {
         String returnType;
         if (attributeIfc instanceof TypedAttribute) {
             Type type = ((TypedAttribute) attributeIfc).getType();
@@ -151,7 +151,7 @@ public class TemplateFactory {
     }
 
     public static GeneralInterfaceTemplate serviceInterfaceFromSie(
-            ServiceInterfaceEntry sie) {
+            final ServiceInterfaceEntry sie) {
 
         List<String> extendedInterfaces = Lists
                 .newArrayList(AbstractServiceInterface.class.getCanonicalName());
@@ -177,7 +177,7 @@ public class TemplateFactory {
     }
 
     public static AbstractFactoryTemplate abstractFactoryTemplateFromMbe(
-            ModuleMXBeanEntry mbe) {
+            final ModuleMXBeanEntry mbe) {
         AbstractFactoryAttributesProcessor attrProcessor = new AbstractFactoryAttributesProcessor();
         attrProcessor.processAttributes(mbe.getAttributes(),
                 mbe.getPackageName());
@@ -191,7 +191,7 @@ public class TemplateFactory {
     }
 
     public static AbstractModuleTemplate abstractModuleTemplateFromMbe(
-            ModuleMXBeanEntry mbe) {
+            final ModuleMXBeanEntry mbe) {
         AbstractModuleAttributesProcessor attrProcessor = new AbstractModuleAttributesProcessor(mbe.getAttributes());
 
         List<ModuleField> moduleFields = attrProcessor.getModuleFields();
@@ -234,7 +234,7 @@ public class TemplateFactory {
     }
 
     public static StubFactoryTemplate stubFactoryTemplateFromMbe(
-            ModuleMXBeanEntry mbe) {
+            final ModuleMXBeanEntry mbe) {
         return new StubFactoryTemplate(getHeaderFromEntry(mbe),
                 mbe.getPackageName(), mbe.getStubFactoryName(),
                 mbe.getFullyQualifiedName(mbe.getAbstractFactoryName())
@@ -242,7 +242,7 @@ public class TemplateFactory {
     }
 
     public static GeneralInterfaceTemplate mXBeanInterfaceTemplateFromMbe(
-            ModuleMXBeanEntry mbe) {
+            final ModuleMXBeanEntry mbe) {
         MXBeanInterfaceAttributesProcessor attrProcessor = new MXBeanInterfaceAttributesProcessor();
         attrProcessor.processAttributes(mbe.getAttributes());
         GeneralInterfaceTemplate ifcTemplate = new GeneralInterfaceTemplate(
@@ -254,7 +254,7 @@ public class TemplateFactory {
     }
 
     public static Map<String, GeneralClassTemplate> tOsFromMbe(
-            ModuleMXBeanEntry mbe) {
+            final ModuleMXBeanEntry mbe) {
         Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
         TOAttributesProcessor processor = new TOAttributesProcessor();
         processor.processAttributes(mbe.getAttributes());
@@ -275,7 +275,7 @@ public class TemplateFactory {
     }
 
     public static Map<String, GeneralClassTemplate> tOsFromRbe(
-            RuntimeBeanEntry rbe) {
+            final RuntimeBeanEntry rbe) {
         Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
         TOAttributesProcessor processor = new TOAttributesProcessor();
         Map<String, AttributeIfc> yangPropertiesToTypesMap = Maps.newHashMap(rbe.getYangPropertiesToTypesMap());
@@ -316,7 +316,7 @@ public class TemplateFactory {
         return retVal;
     }
 
-    private static Header getHeaderFromEntry(AbstractEntry mbe) {
+    private static Header getHeaderFromEntry(final AbstractEntry mbe) {
         return new Header(mbe.getYangModuleName(), mbe.getYangModuleLocalname());
     }
 
@@ -326,7 +326,7 @@ public class TemplateFactory {
 
         private final List<TOInternal> tos = Lists.newArrayList();
 
-        void processAttributes(Map<String, AttributeIfc> attributes) {
+        void processAttributes(final Map<String, AttributeIfc> attributes) {
             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
                 AttributeIfc attributeIfc = attrEntry.getValue();
                 if (attributeIfc instanceof TOAttribute) {
@@ -342,7 +342,7 @@ public class TemplateFactory {
             }
         }
 
-        private void createTOInternal(TOAttribute toAttribute) {
+        private void createTOInternal(final TOAttribute toAttribute) {
 
             Map<String, AttributeIfc> attrs = toAttribute.getCapitalizedPropertiesToTypesMap();
             // recursive processing of TO's attributes
@@ -360,12 +360,12 @@ public class TemplateFactory {
             private List<Field> fields;
             private List<MethodDefinition> methods;
 
-            public TOInternal(Type type, Map<String, AttributeIfc> attrs) {
+            public TOInternal(final Type type, final Map<String, AttributeIfc> attrs) {
                 this(type.getFullyQualifiedName(), type.getName(), attrs, type.getPackageName());
             }
 
-            public TOInternal(String fullyQualifiedName, String name,
-                    Map<String, AttributeIfc> attrs, String packageName) {
+            public TOInternal(final String fullyQualifiedName, final String name,
+                    final Map<String, AttributeIfc> attrs, final String packageName) {
                 this.fullyQualifiedName = fullyQualifiedName;
                 this.name = name;
                 processAttrs(attrs, packageName);
@@ -374,7 +374,7 @@ public class TemplateFactory {
             private final static String dependencyResolverVarName = "dependencyResolver";
             private final static String dependencyResolverInjectMethodName = "injectDependencyResolver";
 
-            private void processAttrs(Map<String, AttributeIfc> attrs, String packageName) {
+            private void processAttrs(final Map<String, AttributeIfc> attrs, final String packageName) {
                 fields = Lists.newArrayList();
                 methods = Lists.newArrayList();
 
@@ -386,8 +386,7 @@ public class TemplateFactory {
 
                 for (Entry<String, AttributeIfc> attrEntry : attrs.entrySet()) {
                     String innerName = attrEntry.getKey();
-                    String varName = BindingGeneratorUtil
-                            .parseToValidParamName(attrEntry.getKey());
+                    String varName = BindingMapping.getPropertyName(attrEntry.getKey());
 
                     String fullyQualifiedName, nullableDefault = null;
                     if (attrEntry.getValue() instanceof TypedAttribute) {
@@ -449,7 +448,7 @@ public class TemplateFactory {
     private static class MXBeanInterfaceAttributesProcessor {
         private final List<MethodDeclaration> methods = Lists.newArrayList();
 
-        void processAttributes(Map<String, AttributeIfc> attributes) {
+        void processAttributes(final Map<String, AttributeIfc> attributes) {
             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
                 String returnType;
                 AttributeIfc attributeIfc = attrEntry.getValue();
@@ -473,8 +472,7 @@ public class TemplateFactory {
                 MethodDeclaration getter = new MethodDeclaration(returnType,
                         getterName, Collections.<Field> emptyList());
 
-                String varName = BindingGeneratorUtil
-                        .parseToValidParamName(attrEntry.getKey());
+                String varName = BindingMapping.getPropertyName(attrEntry.getKey());
                 String setterName = "set"
                         + attributeIfc.getUpperCaseCammelCase();
                 MethodDeclaration setter = new MethodDeclaration("void",
@@ -519,8 +517,8 @@ public class TemplateFactory {
 
         private final List<Field> fields = Lists.newArrayList();
 
-        void processAttributes(Map<String, AttributeIfc> attributes,
-                String packageName) {
+        void processAttributes(final Map<String, AttributeIfc> attributes,
+                final String packageName) {
             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
                 String type;
                 String nullableDefaultWrapped = null;
@@ -550,7 +548,7 @@ public class TemplateFactory {
             private final List<ModuleField> moduleFields;
             private final List<MethodDefinition> methods;
 
-            private Holder(List<ModuleField> moduleFields, List<MethodDefinition> methods) {
+            private Holder(final List<ModuleField> moduleFields, final List<MethodDefinition> methods) {
                 this.moduleFields = Collections.unmodifiableList(moduleFields);
                 this.methods = Collections.unmodifiableList(methods);
             }
@@ -559,11 +557,11 @@ public class TemplateFactory {
         private final Holder holder;
 
 
-        private AbstractModuleAttributesProcessor(Map<String, AttributeIfc> attributes) {
+        private AbstractModuleAttributesProcessor(final Map<String, AttributeIfc> attributes) {
             this.holder = processAttributes(attributes);
         }
 
-        private static Holder processAttributes(Map<String, AttributeIfc> attributes) {
+        private static Holder processAttributes(final Map<String, AttributeIfc> attributes) {
             List<ModuleField> moduleFields = new ArrayList<>();
             List<MethodDefinition> methods = new ArrayList<>();
             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
@@ -607,8 +605,7 @@ public class TemplateFactory {
                     }
                 }
 
-                String varName = BindingGeneratorUtil
-                        .parseToValidParamName(attrEntry.getKey());
+                String varName = BindingMapping.getPropertyName(attrEntry.getKey());
 
                 ModuleField field;
                 if (isIdentity) {
@@ -689,7 +686,7 @@ public class TemplateFactory {
     }
 
 
-    private static boolean needsDepResolver(AttributeIfc value) {
+    private static boolean needsDepResolver(final AttributeIfc value) {
         if(value instanceof TOAttribute) {
             return true;
         }
@@ -701,7 +698,7 @@ public class TemplateFactory {
         return false;
     }
 
-    private static String getInnerTypeFromIdentity(Type type) {
+    private static String getInnerTypeFromIdentity(final Type type) {
         Preconditions.checkArgument(type instanceof ParameterizedType);
         Type[] args = ((ParameterizedType) type).getActualTypeArguments();
         Preconditions.checkArgument(args.length ==1);
index 8e088ba57822b00155b00aad346b93c8f897f64a..ccb72191c43376ebda39b93a35cda0770eecb69c 100644 (file)
@@ -19,7 +19,6 @@
         <dependency>\r
             <groupId>org.opendaylight.controller</groupId>\r
             <artifactId>ietf-netconf-notifications</artifactId>\r
-            <version>0.3.0-SNAPSHOT</version>\r
         </dependency>\r
         <dependency>\r
             <groupId>org.opendaylight.controller</groupId>\r
@@ -95,7 +94,6 @@
             <plugin>\r
                 <groupId>org.codehaus.mojo</groupId>\r
                 <artifactId>build-helper-maven-plugin</artifactId>\r
-                <version>1.8</version>\r
                 <executions>\r
                     <execution>\r
                         <id>add-source</id>\r
index aebde0c0432df8fb3f75085f8cc749d0b8e39bdc..a32413064e429403aeaa9a032845e3a34ee8fbde 100644 (file)
@@ -63,10 +63,7 @@ public class Topic implements DataChangeListener {
     public void notifyNode(final NodeId nodeId) {
         JoinTopicInput jti = getJoinTopicInputArgument(nodeId);
         EventSourceService ess = mdSal.getRpcService(EventSourceService.class);
-
-        if (ess == null) {
-            throw new IllegalStateException("EventSourceService is not registered.");
-        }
+        Preconditions.checkState(ess != null, "EventSourceService is not registered");
 
         ess.joinTopic(jti);
     }
index 1552096ef15aed6bf8f941a1c24474c9ca8cbe44..be51ba069cc5056636646566d1db00b30154073a 100644 (file)
@@ -126,6 +126,9 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior {
         // (heartbeat) to each server; repeat during idle periods to
         // prevent election timeouts (§5.2)
         sendAppendEntries(0, false);
+
+        // It is important to schedule this heartbeat here
+        scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
     }
 
     /**
@@ -304,28 +307,26 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior {
             }
         }
 
-        try {
-            if (message instanceof SendHeartBeat) {
-                beforeSendHeartbeat();
-                sendHeartBeat();
-                return this;
+        if (message instanceof SendHeartBeat) {
+            beforeSendHeartbeat();
+            sendHeartBeat();
+            scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
+            return this;
 
-            } else if(message instanceof SendInstallSnapshot) {
-                // received from RaftActor
-                setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
-                sendInstallSnapshot();
+        } else if(message instanceof SendInstallSnapshot) {
+            // received from RaftActor
+            setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
+            sendInstallSnapshot();
 
-            } else if (message instanceof Replicate) {
-                replicate((Replicate) message);
+        } else if (message instanceof Replicate) {
+            replicate((Replicate) message);
 
-            } else if (message instanceof InstallSnapshotReply){
-                handleInstallSnapshotReply((InstallSnapshotReply) message);
+        } else if (message instanceof InstallSnapshotReply){
+            handleInstallSnapshotReply((InstallSnapshotReply) message);
 
-            }
-        } finally {
-            scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
         }
 
+
         return super.handleMessage(sender, message);
     }
 
index ba8f49d8f6249b5ae3b4340128eeea2a9dc1bc3e..83868b6a2ad187a257bc3323479b8d84974276a5 100644 (file)
@@ -552,7 +552,6 @@ public class RaftActorTest extends AbstractActorTest {
                 assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor());
 
                 mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class));
-
             }};
     }
 
@@ -576,12 +575,12 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar");
 
                 assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS));
-
             }
-
         };
     }
 
@@ -602,14 +601,14 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 MockRaftActorContext.MockReplicatedLogEntry logEntry = new MockRaftActorContext.MockReplicatedLogEntry(10, 10, mock(Payload.class));
 
                 mockRaftActor.getRaftActorContext().getReplicatedLog().appendAndPersist(logEntry);
 
                 verify(dataPersistenceProvider).persist(eq(logEntry), any(Procedure.class));
-
             }
-
         };
     }
 
@@ -630,14 +629,14 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 mockRaftActor.getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
 
                 mockRaftActor.getRaftActorContext().getReplicatedLog().removeFromAndPersist(0);
 
                 verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class));
-
             }
-
         };
     }
 
@@ -658,6 +657,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 mockRaftActor.onReceiveCommand(new ApplyLogEntries(10));
 
                 verify(dataPersistenceProvider, times(1)).persist(anyObject(), any(Procedure.class));
@@ -685,6 +686,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 ByteString snapshotBytes = fromObject(Arrays.asList(
                         new MockRaftActorContext.MockPayload("A"),
                         new MockRaftActorContext.MockPayload("B"),
@@ -722,6 +725,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 1, mock(Payload.class)));
                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 2, mock(Payload.class)));
@@ -783,6 +788,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
                         new MockRaftActorContext.MockPayload("F"));
 
@@ -811,6 +818,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 ReplicatedLog oldReplicatedLog = mockRaftActor.getReplicatedLog();
 
                 oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
@@ -864,6 +873,8 @@ public class RaftActorTest extends AbstractActorTest {
 
                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
 
+                mockRaftActor.waitForInitializeBehaviorComplete();
+
                 ByteString snapshotBytes = fromObject(Arrays.asList(
                         new MockRaftActorContext.MockPayload("A"),
                         new MockRaftActorContext.MockPayload("B"),
@@ -892,17 +903,28 @@ public class RaftActorTest extends AbstractActorTest {
     public void testRaftRoleChangeNotifier() throws Exception {
         new JavaTestKit(getSystem()) {{
             ActorRef notifierActor = factory.createActor(Props.create(MessageCollectorActor.class));
+            MessageCollectorActor.waitUntilReady(notifierActor);
+
             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
+            long heartBeatInterval = 100;
+            config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
+            config.setElectionTimeoutFactor(1);
+
             String persistenceId = factory.generateActorId("notifier-");
 
             factory.createTestActor(MockRaftActor.props(persistenceId,
                     Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), notifierActor), persistenceId);
 
-            // sleeping for a minimum of 2 seconds, if it spans more its fine.
-            Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
+            List<RoleChanged> matches =  null;
+            for(int i = 0; i < 5000 / heartBeatInterval; i++) {
+                matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
+                assertNotNull(matches);
+                if(matches.size() == 3) {
+                    break;
+                }
+                Uninterruptibles.sleepUninterruptibly(heartBeatInterval, TimeUnit.MILLISECONDS);
+            }
 
-            List<RoleChanged> matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
-            assertNotNull(matches);
             assertEquals(3, matches.size());
 
             // check if the notifier got a role change from null to Follower
@@ -944,11 +966,12 @@ public class RaftActorTest extends AbstractActorTest {
                 Map<String, String> peerAddresses = new HashMap<>();
                 peerAddresses.put(follower1Id, followerActor1.path().toString());
 
-                TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(),
+                TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
                         MockRaftActor.props(persistenceId, peerAddresses,
                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
 
                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
+
                 leaderActor.getRaftActorContext().setCommitIndex(4);
                 leaderActor.getRaftActorContext().setLastApplied(4);
                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
@@ -1034,7 +1057,7 @@ public class RaftActorTest extends AbstractActorTest {
                 Map<String, String> peerAddresses = new HashMap<>();
                 peerAddresses.put(leaderId, leaderActor1.path().toString());
 
-                TestActorRef<MockRaftActor> mockActorRef = TestActorRef.create(getSystem(),
+                TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
                         MockRaftActor.props(persistenceId, peerAddresses,
                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
 
diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderTest.java
new file mode 100644 (file)
index 0000000..dd3ed23
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2015 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.cluster.raft.behaviors;
+
+import static org.junit.Assert.assertTrue;
+import akka.actor.ActorRef;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
+import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
+import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
+import org.opendaylight.controller.cluster.raft.utils.ForwardMessageToBehaviorActor;
+import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
+import scala.concurrent.duration.FiniteDuration;
+
+public abstract class AbstractLeaderTest extends AbstractRaftActorBehaviorTest{
+
+    /**
+     * When we removed scheduling of heartbeat in the AbstractLeader constructor we ended up with a situation where
+     * if no follower responded to an initial AppendEntries heartbeats would not be sent to it. This test verifies
+     * that regardless of whether followers respond or not we schedule heartbeats.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void testLeaderSchedulesHeartbeatsEvenWhenNoFollowersRespondToInitialAppendEntries() throws Exception {
+        logStart("testLeaderSchedulesHeartbeatsEvenWhenNoFollowersRespondToInitialAppendEntries");
+        new JavaTestKit(getSystem()) {{
+            String leaderActorId = actorFactory.generateActorId("leader");
+            String follower1ActorId = actorFactory.generateActorId("follower");
+            String follower2ActorId = actorFactory.generateActorId("follower");
+
+            TestActorRef<ForwardMessageToBehaviorActor> leaderActor =
+                    actorFactory.createTestActor(ForwardMessageToBehaviorActor.props(), leaderActorId);
+            ActorRef follower1Actor = actorFactory.createActor(MessageCollectorActor.props(), follower1ActorId);
+            ActorRef follower2Actor = actorFactory.createActor(MessageCollectorActor.props(), follower2ActorId);
+
+            MockRaftActorContext leaderActorContext =
+                    new MockRaftActorContext(leaderActorId, getSystem(), leaderActor);
+
+            DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
+            configParams.setHeartBeatInterval(new FiniteDuration(200, TimeUnit.MILLISECONDS));
+            configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(10, TimeUnit.SECONDS));
+
+            leaderActorContext.setConfigParams(configParams);
+
+            leaderActorContext.setReplicatedLog(
+                    new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(1,5,1).build());
+
+            Map<String, String> peerAddresses = new HashMap<>();
+            peerAddresses.put(follower1ActorId,
+                    follower1Actor.path().toString());
+            peerAddresses.put(follower2ActorId,
+                    follower2Actor.path().toString());
+
+
+            leaderActorContext.setPeerAddresses(peerAddresses);
+
+            RaftActorBehavior leader = createBehavior(leaderActorContext);
+
+            leaderActor.underlyingActor().setBehavior(leader);
+
+            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
+
+            List<SendHeartBeat> allMessages = MessageCollectorActor.getAllMatching(leaderActor, SendHeartBeat.class);
+
+            // Need more than 1 heartbeat to be delivered because we waited for 1 second with heartbeat interval 200ms
+            assertTrue(String.format("%s messages is less than expected", allMessages.size()),
+                    allMessages.size() > 1);
+
+        }};
+    }
+
+}
index b37ace9560b4bfa46984cb030f310541717a2d63..e16d765cdea29a76b0a18440a3128c1a4f2529e6 100644 (file)
@@ -22,7 +22,7 @@ import org.opendaylight.controller.cluster.raft.RaftState;
 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
 
-public class IsolatedLeaderTest  extends AbstractRaftActorBehaviorTest {
+public class IsolatedLeaderTest  extends AbstractLeaderTest {
 
     private final TestActorRef<MessageCollectorActor> leaderActor = actorFactory.createTestActor(
             Props.create(MessageCollectorActor.class), actorFactory.generateActorId("leader"));
@@ -44,7 +44,7 @@ public class IsolatedLeaderTest  extends AbstractRaftActorBehaviorTest {
 
     @Override
     protected RaftActorBehavior createBehavior(RaftActorContext actorContext) {
-        return new Leader(actorContext);
+        return new IsolatedLeader(actorContext);
     }
 
     @Override
index 34e1ed9b3b3478032c86e9058998ac23610c7c97..c57fce1cd553d8c41dd786d9c4bb6f33e97791b6 100644 (file)
@@ -41,11 +41,12 @@ import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
+import org.opendaylight.controller.cluster.raft.utils.ForwardMessageToBehaviorActor;
 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
 import org.opendaylight.controller.protobuff.messages.cluster.raft.InstallSnapshotMessages;
 import scala.concurrent.duration.FiniteDuration;
 
-public class LeaderTest extends AbstractRaftActorBehaviorTest {
+public class LeaderTest extends AbstractLeaderTest {
 
     static final String FOLLOWER_ID = "follower";
 
@@ -742,7 +743,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
 
     private MockRaftActorContext createActorContextWithFollower() {
         MockRaftActorContext actorContext = createActorContext();
-        actorContext.setPeerAddresses(ImmutableMap.<String,String>builder().put(FOLLOWER_ID,
+        actorContext.setPeerAddresses(ImmutableMap.<String, String>builder().put(FOLLOWER_ID,
                 followerActor.path().toString()).build());
         return actorContext;
     }
@@ -756,22 +757,6 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         return context;
     }
 
-    public static class ForwardMessageToBehaviorActor extends MessageCollectorActor {
-        AbstractRaftActorBehavior behavior;
-
-        @Override public void onReceive(Object message) throws Exception {
-            if(behavior != null) {
-                behavior.handleMessage(sender(), message);
-            }
-
-            super.onReceive(message);
-        }
-
-        public static Props props() {
-            return Props.create(ForwardMessageToBehaviorActor.class);
-        }
-    }
-
     @Test
     public void testLeaderCreatedWithCommitIndexLessThanLastIndex() throws Exception {
         logStart("testLeaderCreatedWithCommitIndexLessThanLastIndex");
@@ -781,7 +766,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         MockRaftActorContext followerActorContext = createActorContext(FOLLOWER_ID, followerActor);
 
         Follower follower = new Follower(followerActorContext);
-        followerActor.underlyingActor().behavior = follower;
+        followerActor.underlyingActor().setBehavior(follower);
 
         Map<String, String> peerAddresses = new HashMap<>();
         peerAddresses.put(FOLLOWER_ID, followerActor.path().toString());
@@ -834,7 +819,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         MockRaftActorContext followerActorContext = createActorContext(FOLLOWER_ID, followerActor);
 
         Follower follower = new Follower(followerActorContext);
-        followerActor.underlyingActor().behavior = follower;
+        followerActor.underlyingActor().setBehavior(follower);
 
         Map<String, String> peerAddresses = new HashMap<>();
         peerAddresses.put(FOLLOWER_ID, followerActor.path().toString());
@@ -871,7 +856,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         assertEquals(2, appendEntriesReply.getLogLastIndex());
         assertEquals(1, appendEntriesReply.getLogLastTerm());
 
-        leaderActor.underlyingActor().behavior = leader;
+        leaderActor.underlyingActor().setBehavior(follower);
         leader.handleMessage(followerActor, appendEntriesReply);
 
         leaderActor.underlyingActor().clear();
@@ -1076,7 +1061,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         followerActorContext.setConfigParams(configParams);
 
         Follower follower = new Follower(followerActorContext);
-        followerActor.underlyingActor().behavior = follower;
+        followerActor.underlyingActor().setBehavior(follower);
 
         leaderActorContext.getReplicatedLog().removeFrom(0);
         leaderActorContext.setCommitIndex(-1);
@@ -1134,6 +1119,66 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest {
         follower.close();
     }
 
+    @Test
+    public void testLaggingFollowerStarvation() throws Exception {
+        logStart("testLaggingFollowerStarvation");
+        new JavaTestKit(getSystem()) {{
+            String leaderActorId = actorFactory.generateActorId("leader");
+            String follower1ActorId = actorFactory.generateActorId("follower");
+            String follower2ActorId = actorFactory.generateActorId("follower");
+
+            TestActorRef<ForwardMessageToBehaviorActor> leaderActor =
+                    actorFactory.createTestActor(ForwardMessageToBehaviorActor.props(), leaderActorId);
+            ActorRef follower1Actor = actorFactory.createActor(MessageCollectorActor.props(), follower1ActorId);
+            ActorRef follower2Actor = actorFactory.createActor(MessageCollectorActor.props(), follower2ActorId);
+
+            MockRaftActorContext leaderActorContext =
+                    new MockRaftActorContext(leaderActorId, getSystem(), leaderActor);
+
+            DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
+            configParams.setHeartBeatInterval(new FiniteDuration(200, TimeUnit.MILLISECONDS));
+            configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(10, TimeUnit.SECONDS));
+
+            leaderActorContext.setConfigParams(configParams);
+
+            leaderActorContext.setReplicatedLog(
+                    new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(1,5,1).build());
+
+            Map<String, String> peerAddresses = new HashMap<>();
+            peerAddresses.put(follower1ActorId,
+                    follower1Actor.path().toString());
+            peerAddresses.put(follower2ActorId,
+                    follower2Actor.path().toString());
+
+            leaderActorContext.setPeerAddresses(peerAddresses);
+            leaderActorContext.getTermInformation().update(1, leaderActorId);
+
+            RaftActorBehavior leader = createBehavior(leaderActorContext);
+
+            leaderActor.underlyingActor().setBehavior(leader);
+
+            for(int i=1;i<6;i++) {
+                // Each AppendEntriesReply could end up rescheduling the heartbeat (without the fix for bug 2733)
+                RaftActorBehavior newBehavior = leader.handleMessage(follower1Actor, new AppendEntriesReply(follower1ActorId, 1, true, i, 1));
+                assertTrue(newBehavior == leader);
+                Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
+            }
+
+            // Check if the leader has been receiving SendHeartbeat messages despite getting AppendEntriesReply
+            List<SendHeartBeat> heartbeats = MessageCollectorActor.getAllMatching(leaderActor, SendHeartBeat.class);
+
+            assertTrue(String.format("%s heartbeat(s) is less than expected", heartbeats.size()),
+                    heartbeats.size() > 1);
+
+            // Check if follower-2 got AppendEntries during this time and was not starved
+            List<AppendEntries> appendEntries = MessageCollectorActor.getAllMatching(follower2Actor, AppendEntries.class);
+
+            assertTrue(String.format("%s append entries is less than expected", appendEntries.size()),
+                    appendEntries.size() > 1);
+
+        }};
+    }
+
     @Override
     protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(RaftActorContext actorContext,
             ActorRef actorRef, RaftRPC rpc) throws Exception {
diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/ForwardMessageToBehaviorActor.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/ForwardMessageToBehaviorActor.java
new file mode 100644 (file)
index 0000000..9bcfcd9
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2015 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.cluster.raft.utils;
+
+import akka.actor.Props;
+import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
+
+public class ForwardMessageToBehaviorActor extends MessageCollectorActor {
+    private RaftActorBehavior behavior;
+
+    @Override
+    public void onReceive(Object message) throws Exception {
+        if(behavior != null) {
+            behavior.handleMessage(sender(), message);
+        }
+
+        super.onReceive(message);
+    }
+
+    public static Props props() {
+        return Props.create(ForwardMessageToBehaviorActor.class);
+    }
+
+    public void setBehavior(RaftActorBehavior behavior){
+        this.behavior = behavior;
+    }
+}
+
index 662c12180d29acc65851f6a28e64590ffe2b5463..62f163fb7d0270a2415e934d193136d610e01ca3 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.cluster.raft.utils;
 
 import akka.actor.ActorRef;
+import akka.actor.Props;
 import akka.actor.UntypedActor;
 import akka.pattern.Patterns;
 import akka.util.Timeout;
@@ -123,4 +124,8 @@ public class MessageCollectorActor extends UntypedActor {
 
         throw new TimeoutException("Actor not ready in time.");
     }
+
+    public static Props props() {
+        return Props.create(MessageCollectorActor.class);
+    }
 }
index 2f02f981ab198fe248a33a33ac90187b57064211..2a7c8b6682cbdaf0a9f0a8ff7cd194a9f22c5c12 100644 (file)
@@ -60,8 +60,8 @@ public class DOMBrokerPerformanceTest {
 
     @Before
     public void setupStore() {
-        InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
-        InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
+        InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
+        InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
         schemaContext = TestModel.createTestContext();
 
         operStore.onGlobalContextUpdated(schemaContext);
index c1d301c549b8cd1964f9b296cf9e13a3a2d29774..cd8ac0998052f73c94a558443b3663583e82125b 100644 (file)
@@ -57,9 +57,9 @@ public class DOMBrokerTest {
     public void setupStore() {
 
         InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
-                MoreExecutors.sameThreadExecutor());
+                MoreExecutors.newDirectExecutorService());
         InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
-                MoreExecutors.sameThreadExecutor());
+                MoreExecutors.newDirectExecutorService());
         schemaContext = TestModel.createTestContext();
 
         operStore.onGlobalContextUpdated(schemaContext);
index 03d39a2a62a33cf5b61f468401a338b77133d622..aba78f755912275c1cf001e8225fe02ac7b9b0f6 100644 (file)
@@ -41,8 +41,8 @@ public class DOMTransactionChainTest {
 
     @Before
     public void setupStore() {
-        InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
-        InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
+        InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
+        InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
         schemaContext = TestModel.createTestContext();
 
         operStore.onGlobalContextUpdated(schemaContext);
index c7ee3a5c0c8a2346dabae2c4045a67839a4ab312..85ae59b161f6646d964d790a5a6fc2c38560c873 100644 (file)
@@ -81,7 +81,6 @@
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
-      <version>${slf4j.version}</version>
       <scope>test</scope>
     </dependency>
 
@@ -94,7 +93,6 @@
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
-      <version>1.7.7</version>
     </dependency>
 
   </dependencies>
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-shade-plugin</artifactId>
-            <version>1.5</version>
             <executions>
                 <execution>
                     <phase>package</phase>
index 4720f4b4b9f4fcc0c04cad1b2470f2fb15097006..9de4892d9140b1afc7ea3a93ef532ca1bf97edeb 100644 (file)
@@ -45,7 +45,7 @@ public class InMemoryDataStoreTest {
 
     @Before
     public void setupStore() {
-        domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor());
+        domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.newDirectExecutorService());
         schemaContext = TestModel.createTestContext();
         domStore.onGlobalContextUpdated(schemaContext);
     }
index 15e5f716f62c17ccb66d29f09430d8aa4dac7f5b..e7af4dffae98b0b0543a8919c8ead80c6132512a 100644 (file)
@@ -31,7 +31,7 @@ public class SchemaUpdateForTransactionTest {
 
     @Before
     public void setupStore() {
-        domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.sameThreadExecutor());
+        domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.newDirectExecutorService());
         loadSchemas(RockTheHouseInput.class);
     }
 
index f6e6461bf54707d48fc767d411e321c0672733af..a01933c295bea088f5f86e7f0ad417f4d4e2be58 100644 (file)
@@ -8,10 +8,9 @@
 
 package org.opendaylight.controller.md.sal.dom.store.impl;
 
-import java.util.concurrent.ExecutorService;
-
 import com.google.common.util.concurrent.ForwardingExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
+import java.util.concurrent.ExecutorService;
 
 /**
  * A forwarding Executor used by unit tests for DataChangeListener notifications
@@ -21,13 +20,13 @@ import com.google.common.util.concurrent.MoreExecutors;
 public class TestDCLExecutorService extends ForwardingExecutorService {
 
     // Start with a same thread executor to avoid timing issues during test setup.
-    private volatile ExecutorService currentExecutor = MoreExecutors.sameThreadExecutor();
+    private volatile ExecutorService currentExecutor = MoreExecutors.newDirectExecutorService();
 
     // The real executor to use when test setup is complete.
     private final ExecutorService postSetupExecutor;
 
 
-    public TestDCLExecutorService( ExecutorService postSetupExecutor ) {
+    public TestDCLExecutorService( final ExecutorService postSetupExecutor ) {
         this.postSetupExecutor = postSetupExecutor;
     }
 
index b966fae3d4e458f55796fbc0e6e26213b093bd83..44b2435da2284358b4a2ed13cbb6e699e23f2115 100644 (file)
@@ -111,7 +111,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
                 new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
 
         final NetconfDevice device =
-                new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, new NetconfMessageTransformer(), true);
+                new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, new NetconfMessageTransformer(), getReconnectOnChangedSchema());
 
         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
                 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
index 82c04a50e09c9124773d565fc58f2e82b17cd9ff..590f4c4ceb038b2a70f72c2379d5e759bc285db6 100644 (file)
@@ -8,10 +8,19 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
+import com.google.common.base.Optional;
 import java.lang.management.ManagementFactory;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
 import javax.management.MBeanServer;
 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
+import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.yangtools.yang.model.api.Module;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -68,4 +77,117 @@ public class NetconfOperationServiceFactoryImpl implements NetconfOperationServi
     public NetconfOperationServiceImpl createService(String netconfSessionIdForReporting) {
         return new NetconfOperationServiceImpl(yangStoreService, jmxClient, netconfSessionIdForReporting);
     }
+
+
+    @Override
+    public Set<Capability> getCapabilities() {
+        return setupCapabilities(yangStoreService);
+    }
+
+    @Override
+    public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+        return yangStoreService.registerCapabilityListener(listener);
+    }
+
+    public static Set<Capability> setupCapabilities(final YangStoreContext yangStoreSnapshot) {
+        Set<Capability> capabilities = new HashSet<>();
+        // [RFC6241] 8.3.  Candidate Configuration Capability
+        capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+
+        // TODO rollback on error not supported EditConfigXmlParser:100
+        // [RFC6241] 8.5.  Rollback-on-Error Capability
+        // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
+
+        Set<Module> modules = yangStoreSnapshot.getModules();
+        for (Module module : modules) {
+            capabilities.add(new YangStoreCapability(module, yangStoreSnapshot.getModuleSource(module)));
+        }
+
+        return capabilities;
+    }
+
+    private static class BasicCapability implements Capability {
+
+        private final String capability;
+
+        private BasicCapability(final String capability) {
+            this.capability = capability;
+        }
+
+        @Override
+        public String getCapabilityUri() {
+            return capability;
+        }
+
+        @Override
+        public Optional<String> getModuleNamespace() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getModuleName() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getRevision() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getCapabilitySchema() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Collection<String> getLocation() {
+            return Collections.emptyList();
+        }
+
+        @Override
+        public String toString() {
+            return capability;
+        }
+    }
+
+    static final class YangStoreCapability extends BasicCapability {
+
+        private final String content;
+        private final String revision;
+        private final String moduleName;
+        private final String moduleNamespace;
+
+        public YangStoreCapability(final Module module, final String moduleContent) {
+            super(toCapabilityURI(module));
+            this.content = moduleContent;
+            this.moduleName = module.getName();
+            this.moduleNamespace = module.getNamespace().toString();
+            this.revision = Util.writeDate(module.getRevision());
+        }
+
+        @Override
+        public Optional<String> getCapabilitySchema() {
+            return Optional.of(content);
+        }
+
+        private static String toCapabilityURI(final Module module) {
+            return String.valueOf(module.getNamespace()) + "?module="
+                    + module.getName() + "&revision=" + Util.writeDate(module.getRevision());
+        }
+
+        @Override
+        public Optional<String> getModuleName() {
+            return Optional.of(moduleName);
+        }
+
+        @Override
+        public Optional<String> getModuleNamespace() {
+            return Optional.of(moduleNamespace);
+        }
+
+        @Override
+        public Optional<String> getRevision() {
+            return Optional.of(revision);
+        }
+    }
 }
index ef0a72c0f05f44bc2d040a1a03ea0fe2c1af1d0a..28001851ccf2695b0d9ed69c98a6871e6e0ba7f4 100644 (file)
@@ -8,18 +8,11 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
-import com.google.common.base.Optional;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
 import java.util.Set;
 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.yangtools.yang.model.api.Module;
 
 /**
  * Manages life cycle of {@link YangStoreContext}.
@@ -28,132 +21,23 @@ public class NetconfOperationServiceImpl implements NetconfOperationService {
 
     private final NetconfOperationProvider operationProvider;
     private final TransactionProvider transactionProvider;
-    private final YangStoreService yangStoreService;
 
     public NetconfOperationServiceImpl(final YangStoreService yangStoreService, final ConfigRegistryJMXClient jmxClient,
             final String netconfSessionIdForReporting) {
 
-        this.yangStoreService = yangStoreService;
-
         transactionProvider = new TransactionProvider(jmxClient, netconfSessionIdForReporting);
         operationProvider = new NetconfOperationProvider(yangStoreService, jmxClient, transactionProvider,
                 netconfSessionIdForReporting);
     }
 
-    @Override
-    public void close() {
-        transactionProvider.close();
-    }
-
-    @Override
-    public Set<Capability> getCapabilities() {
-        return setupCapabilities(yangStoreService);
-    }
-
     @Override
     public Set<NetconfOperation> getNetconfOperations() {
         return operationProvider.getOperations();
     }
 
-    private static Set<Capability> setupCapabilities(final YangStoreContext yangStoreSnapshot) {
-        Set<Capability> capabilities = new HashSet<>();
-        // [RFC6241] 8.3.  Candidate Configuration Capability
-        capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
-
-        // TODO rollback on error not supported EditConfigXmlParser:100
-        // [RFC6241] 8.5.  Rollback-on-Error Capability
-        // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
-
-        Set<Module> modules = yangStoreSnapshot.getModules();
-        for (Module module : modules) {
-            capabilities.add(new YangStoreCapability(module, yangStoreSnapshot.getModuleSource(module)));
-        }
-
-        return capabilities;
-    }
-
-    private static class BasicCapability implements Capability {
-
-        private final String capability;
-
-        private BasicCapability(final String capability) {
-            this.capability = capability;
-        }
-
-        @Override
-        public String getCapabilityUri() {
-            return capability;
-        }
-
-        @Override
-        public Optional<String> getModuleNamespace() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getModuleName() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getRevision() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getCapabilitySchema() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Collection<String> getLocation() {
-            return Collections.emptyList();
-        }
-
-        @Override
-        public String toString() {
-            return capability;
-        }
+    @Override
+    public void close() {
+        transactionProvider.close();
     }
 
-    private static final class YangStoreCapability extends BasicCapability {
-
-        private final String content;
-        private final String revision;
-        private final String moduleName;
-        private final String moduleNamespace;
-
-        public YangStoreCapability(final Module module, final String moduleContent) {
-            super(toCapabilityURI(module));
-            this.content = moduleContent;
-            this.moduleName = module.getName();
-            this.moduleNamespace = module.getNamespace().toString();
-            this.revision = Util.writeDate(module.getRevision());
-        }
-
-        @Override
-        public Optional<String> getCapabilitySchema() {
-            return Optional.of(content);
-        }
-
-        private static String toCapabilityURI(final Module module) {
-            return String.valueOf(module.getNamespace()) + "?module="
-                    + module.getName() + "&revision=" + Util.writeDate(module.getRevision());
-        }
-
-        @Override
-        public Optional<String> getModuleName() {
-            return Optional.of(moduleName);
-        }
-
-        @Override
-        public Optional<String> getModuleNamespace() {
-            return Optional.of(moduleNamespace);
-        }
-
-        @Override
-        public Optional<String> getRevision() {
-            return Optional.of(revision);
-        }
-    }
 }
index de151a896991f9ffc12a97df1a6bf41ece5e92a9..60b8b8f468b3a42938328fd65fa3e50b534186fd 100644 (file)
@@ -14,6 +14,7 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import java.lang.ref.SoftReference;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ExecutorService;
@@ -21,6 +22,8 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicReference;
 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
 import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
 import org.opendaylight.controller.netconf.notifications.BaseNotificationPublisherRegistration;
 import org.opendaylight.controller.netconf.notifications.NetconfNotificationCollector;
@@ -77,6 +80,8 @@ public class YangStoreService implements YangStoreContext {
         }
     });
 
+    private final Set<CapabilityListener> listeners = Collections.synchronizedSet(new HashSet<CapabilityListener>());
+
     public YangStoreService(final SchemaContextProvider schemaContextProvider, final BundleContext context) {
         this(schemaContextProvider, new NotificationCollectorTracker(context));
     }
@@ -130,7 +135,31 @@ public class YangStoreService implements YangStoreContext {
         notificationExecutor.submit(new CapabilityChangeNotifier(previous));
     }
 
+    public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+        if(ref.get() == null || ref.get().get() == null) {
+            getYangStoreSnapshot();
+        }
+
+        this.listeners.add(listener);
+        listener.onCapabilitiesAdded(NetconfOperationServiceFactoryImpl.setupCapabilities(ref.get().get()));
+
+        return new AutoCloseable() {
+            @Override
+            public void close() throws Exception {
+                YangStoreService.this.listeners.remove(listener);
+            }
+        };
+    }
+
+    private static final Function<Module, Capability> MODULE_TO_CAPABILITY = new Function<Module, Capability>() {
+        @Override
+        public Capability apply(final Module module) {
+            return new NetconfOperationServiceFactoryImpl.YangStoreCapability(module, module.getSource());
+        }
+    };
+
     private final class CapabilityChangeNotifier implements Runnable {
+
         private final YangStoreSnapshot previous;
 
         public CapabilityChangeNotifier(final YangStoreSnapshot previous) {
@@ -142,7 +171,19 @@ public class YangStoreService implements YangStoreContext {
             final YangStoreContext current = getYangStoreSnapshot();
 
             if(current.equals(previous) == false) {
-                notificationPublisher.onCapabilityChanged(computeDiff(previous, current));
+                final Sets.SetView<Module> removed = Sets.difference(previous.getModules(), current.getModules());
+                final Sets.SetView<Module> added = Sets.difference(current.getModules(), previous.getModules());
+
+                // Notify notification manager
+                notificationPublisher.onCapabilityChanged(computeDiff(removed, added));
+
+                // Notify direct capability listener TODO would it not be better if the capability listeners went through notification manager ?
+                for (final CapabilityListener listener : listeners) {
+                    listener.onCapabilitiesAdded(Sets.newHashSet(Collections2.transform(added, MODULE_TO_CAPABILITY)));
+                }
+                for (final CapabilityListener listener : listeners) {
+                    listener.onCapabilitiesRemoved(Sets.newHashSet(Collections2.transform(removed, MODULE_TO_CAPABILITY)));
+                }
             }
         }
     }
@@ -155,10 +196,7 @@ public class YangStoreService implements YangStoreContext {
         }
     };
 
-    static NetconfCapabilityChange computeDiff(final YangStoreContext previous, final YangStoreContext current) {
-        final Sets.SetView<Module> removed = Sets.difference(previous.getModules(), current.getModules());
-        final Sets.SetView<Module> added = Sets.difference(current.getModules(), previous.getModules());
-
+    static NetconfCapabilityChange computeDiff(final Sets.SetView<Module> removed, final Sets.SetView<Module> added) {
         final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
         netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
         netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, MODULE_TO_URI)));
index f1fc27725be99f1a95402f86b2b023e33fb1ecc8..b1222997fb8d944eeb6f4e4b489262e082698ecc 100644 (file)
@@ -95,8 +95,8 @@ import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStore
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -141,7 +141,9 @@ public class NetconfMappingTest extends AbstractConfigTest {
     @Mock
     NetconfOperationRouter netconfOperationRouter;
     @Mock
-    NetconfOperationServiceSnapshotImpl netconfOperationServiceSnapshot;
+    AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
+    @Mock
+    private AutoCloseable sessionCloseable;
 
     private TransactionProvider transactionProvider;
 
@@ -157,13 +159,12 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
         doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
         doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
-        doNothing().when(netconfOperationServiceSnapshot).close();
 
         this.factory = new NetconfTestImplModuleFactory();
         this.factory2 = new DepTestImplModuleFactory();
         this.factory3 = new IdentityTestModuleFactory();
         factory4 = new TestImplModuleFactory();
-
+        doNothing().when(sessionCloseable).close();
 
         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
                 this.factory3, factory4));
@@ -376,7 +377,7 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
         edit("netconfMessages/editConfig_none.xml");
         closeSession();
-        verify(netconfOperationServiceSnapshot).close();
+        verify(sessionCloseable).close();
         verifyNoMoreInteractions(netconfOperationRouter);
         verifyNoMoreInteractions(netconfOperationServiceSnapshot);
     }
@@ -390,7 +391,7 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
     private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
             IOException {
-        DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, netconfOperationServiceSnapshot);
+        DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
         executeOp(closeOp, "netconfMessages/closeSession.xml");
     }
 
index 0aebc68bbe3f653d9a738a3ec6121ee0c162d2a9..22b061a1285c88d0ea372a5c104a2baf69fcb58c 100644 (file)
@@ -33,10 +33,10 @@ import org.opendaylight.controller.config.api.ConflictingVersionException;
 import org.opendaylight.controller.config.persist.api.ConfigPusher;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -177,20 +177,20 @@ public class ConfigPusherImpl implements ConfigPusher {
         } catch(RuntimeException e) {
             throw new NotEnoughCapabilitiesException("Netconf service not stable for " + idForReporting, e);
         }
-        Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, serviceCandidate);
+        Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, configNetconfConnector);
         if (notFoundDiff.isEmpty()) {
             return serviceCandidate;
         } else {
             serviceCandidate.close();
             LOG.trace("Netconf server did not provide required capabilities for {} ", idForReporting,
                     "Expected but not found: {}, all expected {}, current {}",
-                     notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities()
+                     notFoundDiff, expectedCapabilities, configNetconfConnector.getCapabilities()
             );
             throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff);
         }
     }
 
-    private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationService serviceCandidate) {
+    private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationServiceFactory serviceCandidate) {
         Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
             @Override
             public String apply(@Nonnull final Capability input) {
index 787f8b10b077612c544a6efcaad813c304ce0c9f..b27bec3c83801a275810e689e0daabbd7b458f47 100644 (file)
@@ -13,10 +13,10 @@ import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import javax.management.MBeanServer;
 import org.opendaylight.controller.config.persist.api.ConfigPusher;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.persist.impl.ConfigPusherImpl;
 import org.opendaylight.controller.netconf.persist.impl.PersisterAggregator;
@@ -70,7 +70,7 @@ public class ConfigPersisterActivator implements BundleActivator {
         InnerCustomizer innerCustomizer = new InnerCustomizer(configs, maxWaitForCapabilitiesMillis,
                 conflictingVersionTimeoutMillis, persisterAggregator);
         OuterCustomizer outerCustomizer = new OuterCustomizer(context, innerCustomizer);
-        new ServiceTracker<>(context, NetconfOperationProvider.class, outerCustomizer).open();
+        new ServiceTracker<>(context, NetconfOperationServiceFactory.class, outerCustomizer).open();
     }
 
     private long getConflictingVersionTimeoutMillis(PropertiesProviderBaseImpl propertiesProvider) {
@@ -103,7 +103,7 @@ public class ConfigPersisterActivator implements BundleActivator {
                 ")";
     }
 
-    class OuterCustomizer implements ServiceTrackerCustomizer<NetconfOperationProvider, NetconfOperationProvider> {
+    class OuterCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
         private final BundleContext context;
         private final InnerCustomizer innerCustomizer;
 
@@ -113,7 +113,7 @@ public class ConfigPersisterActivator implements BundleActivator {
         }
 
         @Override
-        public NetconfOperationProvider addingService(ServiceReference<NetconfOperationProvider> reference) {
+        public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
             LOG.trace("Got OuterCustomizer.addingService {}", reference);
             // JMX was registered, track config-netconf-connector
             Filter filter;
@@ -127,12 +127,12 @@ public class ConfigPersisterActivator implements BundleActivator {
         }
 
         @Override
-        public void modifiedService(ServiceReference<NetconfOperationProvider> reference, NetconfOperationProvider service) {
+        public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
 
         }
 
         @Override
-        public void removedService(ServiceReference<NetconfOperationProvider> reference, NetconfOperationProvider service) {
+        public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
 
         }
     }
@@ -141,7 +141,9 @@ public class ConfigPersisterActivator implements BundleActivator {
         private final List<ConfigSnapshotHolder> configs;
         private final PersisterAggregator persisterAggregator;
         private final long maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis;
-
+        // This inner customizer has its filter to find the right operation service, but it gets triggered after any
+        // operation service appears. This means that it could start pushing thread up to N times (N = number of operation services spawned in OSGi)
+        private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
 
         InnerCustomizer(List<ConfigSnapshotHolder> configs, long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis,
                         PersisterAggregator persisterAggregator) {
@@ -153,6 +155,10 @@ public class ConfigPersisterActivator implements BundleActivator {
 
         @Override
         public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
+            if(alreadyStarted.compareAndSet(false, true) == false) {
+                //Prevents multiple calls to this method spawning multiple pushing threads
+                return reference.getBundle().getBundleContext().getService(reference);
+            }
             LOG.trace("Got InnerCustomizer.addingService {}", reference);
             NetconfOperationServiceFactory service = reference.getBundle().getBundleContext().getService(reference);
 
@@ -196,10 +202,12 @@ public class ConfigPersisterActivator implements BundleActivator {
 
         @Override
         public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
+            LOG.trace("Got InnerCustomizer.modifiedService {}", reference);
         }
 
         @Override
         public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
+            LOG.trace("Got InnerCustomizer.removedService {}", reference);
         }
 
     }
index 142d8f5226d0f7141336dcfc181428f59bd0bf42..7b79e41f380af45f8a41a1347b8816516fe8bc32 100644 (file)
@@ -20,8 +20,8 @@ import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -41,9 +41,10 @@ public class ConfigPersisterTest {
     private TestingExceptionHandler handler;
 
 
-    private void setUpContextAndStartPersister(String requiredCapability) throws Exception {
+    private void setUpContextAndStartPersister(String requiredCapability, final NetconfOperationService conflictingService) throws Exception {
         DummyAdapterWithInitialSnapshot.expectedCapability = requiredCapability;
         ctx = new MockedBundleContext(1000, 1000);
+        doReturn(getConflictingService()).when(ctx.serviceFactory).createService(anyString());
         configPersisterActivator = new ConfigPersisterActivator();
         configPersisterActivator.start(ctx.getBundleContext());
     }
@@ -62,7 +63,7 @@ public class ConfigPersisterTest {
 
     @Test
     public void testPersisterNotAllCapabilitiesProvided() throws Exception {
-        setUpContextAndStartPersister("required-cap");
+        setUpContextAndStartPersister("required-cap", getConflictingService());
         Thread.sleep(2000);
         handler.assertException(IllegalStateException.class, "Max wait for capabilities reached.Not enough capabilities " +
                 "for <data><config-snapshot/></data>. Expected but not found: [required-cap]");
@@ -71,7 +72,7 @@ public class ConfigPersisterTest {
 
     @Test
     public void testPersisterSuccessfulPush() throws Exception {
-        setUpContextAndStartPersister("cap1");
+        setUpContextAndStartPersister("cap1", getConflictingService());
         NetconfOperationService service = getWorkingService(getOKDocument());
         doReturn(service).when(ctx.serviceFactory).createService(anyString());
         Thread.sleep(2000);
@@ -86,7 +87,7 @@ public class ConfigPersisterTest {
     public NetconfOperationService getWorkingService(Document document) throws SAXException, IOException, NetconfDocumentedException {
         NetconfOperationService service = mock(NetconfOperationService.class);
         Capability capability = mock(Capability.class);
-        doReturn(Sets.newHashSet(capability)).when(service).getCapabilities();
+//        doReturn(Sets.newHashSet(capability)).when(service).getCapabilities();
         doReturn("cap1").when(capability).getCapabilityUri();
 
 
@@ -109,9 +110,8 @@ public class ConfigPersisterTest {
 
     @Test
     public void testPersisterConflictingVersionException() throws Exception {
-        setUpContextAndStartPersister("cap1");
+        setUpContextAndStartPersister("cap1", getConflictingService());
 
-        doReturn(getConflictingService()).when(ctx.serviceFactory).createService(anyString());
         Thread.sleep(2000);
         handler.assertException(IllegalStateException.class, "Max wait for conflicting version stabilization timeout");
     }
@@ -131,7 +131,7 @@ public class ConfigPersisterTest {
 
     @Test
     public void testSuccessConflictingVersionException() throws Exception {
-        setUpContextAndStartPersister("cap1");
+        setUpContextAndStartPersister("cap1", getConflictingService());
         doReturn(getConflictingService()).when(ctx.serviceFactory).createService(anyString());
         Thread.sleep(500);
         // working service:
index 0d866ecda7ee7349c1f470be5b110a3ab4a9376b..bd18c8c30e8791dc08a5e6e4a3eceb82a1f7de6c 100644 (file)
@@ -12,6 +12,7 @@ import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
 
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
@@ -28,7 +29,7 @@ import org.opendaylight.controller.config.persist.api.ConfigPusher;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.api.Persister;
 import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.persist.impl.DummyAdapter;
@@ -60,11 +61,11 @@ final class MockedBundleContext {
         doReturn(null).when(context).getProperty(anyString());
         initContext(maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
 
-        String outerFilterString = "(objectClass=org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider)";
+        String outerFilterString = "(objectClass=org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory)";
         doReturn(outerFilter).when(context).createFilter(outerFilterString);
         doNothing().when(context).addServiceListener(any(ServiceListener.class), eq(outerFilterString));
         ServiceReference<?>[] toBeReturned = {serviceReference};
-        doReturn(toBeReturned).when(context).getServiceReferences(NetconfOperationProvider.class.getName(), null);
+        doReturn(toBeReturned).when(context).getServiceReferences(NetconfOperationServiceFactory.class.getName(), null);
 
         String innerFilterString = "innerfilter";
         doReturn(innerFilterString).when(outerFilter).toString();
@@ -77,9 +78,12 @@ final class MockedBundleContext {
         doReturn(bundle).when(serviceReference).getBundle();
         doReturn(context).when(bundle).getBundleContext();
         doReturn("").when(serviceReference).toString();
+        doReturn("context").when(context).toString();
         doReturn(serviceFactory).when(context).getService(any(ServiceReference.class));
         doReturn(service).when(serviceFactory).createService(anyString());
-        doReturn(Collections.emptySet()).when(service).getCapabilities();
+        final Capability cap = mock(Capability.class);
+        doReturn("cap1").when(cap).getCapabilityUri();
+        doReturn(Collections.singleton(cap)).when(serviceFactory).getCapabilities();
         doNothing().when(service).close();
         doReturn("serviceFactoryMock").when(serviceFactory).toString();
 
index f54c5e9838b21549199633ec699e4ae953b2aaa9..cc22dd51aaa5c8bdbcaffda3ba09d2ac509a68e4 100644 (file)
@@ -8,34 +8,17 @@
 
 package org.opendaylight.controller.netconf.mdsal.connector;
 
-import com.google.common.base.Optional;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
 import java.util.Set;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public class MdsalNetconfOperationService implements NetconfOperationService {
 
-    private static final Logger LOG = LoggerFactory.getLogger(MdsalNetconfOperationService.class);
-
-    private final CurrentSchemaContext schemaContext;
-    private final String netconfSessionIdForReporting;
     private final OperationProvider operationProvider;
 
     public MdsalNetconfOperationService(final CurrentSchemaContext schemaContext, final String netconfSessionIdForReporting,
                                         final DOMDataBroker dataBroker) {
-        this.schemaContext = schemaContext;
-        // TODO schema contexts are different in data broker and the one we receive here ... the one received here should be updated same way as broker is
-        this.netconfSessionIdForReporting = netconfSessionIdForReporting;
         this.operationProvider = new OperationProvider(netconfSessionIdForReporting, schemaContext, dataBroker);
     }
 
@@ -44,115 +27,9 @@ public class MdsalNetconfOperationService implements NetconfOperationService {
 
     }
 
-    // TODO does this get called dynamically ?
-    @Override
-    public Set<Capability> getCapabilities() {
-        final Set<Capability> capabilities = new HashSet<>();
-        // [RFC6241] 8.3.  Candidate Configuration Capability
-        capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
-
-        final SchemaContext currentContext = schemaContext.getCurrentContext();
-        final Set<Module> modules = currentContext.getModules();
-        for (final Module module : modules) {
-            if(currentContext.getModuleSource(module).isPresent()) {
-                capabilities.add(new YangStoreCapability(module, currentContext.getModuleSource(module).get()));
-            } else {
-                LOG.warn("Missing source for module {}. This module will not be available from netconf server for session {}",
-                        module, netconfSessionIdForReporting);
-            }
-        }
-
-        return capabilities;
-    }
-
     @Override
     public Set<NetconfOperation> getNetconfOperations() {
         return operationProvider.getOperations();
     }
 
-    // TODO reuse from netconf impl
-    private static class BasicCapability implements Capability {
-
-        private final String capability;
-
-        private BasicCapability(final String capability) {
-            this.capability = capability;
-        }
-
-        @Override
-        public String getCapabilityUri() {
-            return capability;
-        }
-
-        @Override
-        public Optional<String> getModuleNamespace() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getModuleName() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getRevision() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Optional<String> getCapabilitySchema() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Collection<String> getLocation() {
-            return Collections.emptyList();
-        }
-
-        @Override
-        public String toString() {
-            return capability;
-        }
-    }
-
-    private static final class YangStoreCapability extends BasicCapability {
-
-        private final String content;
-        private final String revision;
-        private final String moduleName;
-        private final String moduleNamespace;
-
-        public YangStoreCapability(final Module module, final String moduleContent) {
-            super(toCapabilityURI(module));
-            this.content = moduleContent;
-            this.moduleName = module.getName();
-            this.moduleNamespace = module.getNamespace().toString();
-            this.revision = SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision());
-        }
-
-        @Override
-        public Optional<String> getCapabilitySchema() {
-            return Optional.of(content);
-        }
-
-        private static String toCapabilityURI(final Module module) {
-            return String.valueOf(module.getNamespace()) + "?module="
-                    + module.getName() + "&revision=" + SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision());
-        }
-
-        @Override
-        public Optional<String> getModuleName() {
-            return Optional.of(moduleName);
-        }
-
-        @Override
-        public Optional<String> getModuleNamespace() {
-            return Optional.of(moduleNamespace);
-        }
-
-        @Override
-        public Optional<String> getRevision() {
-            return Optional.of(revision);
-        }
-    }
 }
index 098f25bf4a9216adeba96833e06d497b65cb4539..9bd71c3c7ca9d893289f1753a59fc61403a44657 100644 (file)
@@ -8,13 +8,27 @@
 
 package org.opendaylight.controller.netconf.mdsal.connector;
 
+import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class MdsalNetconfOperationServiceFactory implements NetconfOperationServiceFactory, AutoCloseable {
 
+    private static final Logger LOG = LoggerFactory.getLogger(MdsalNetconfOperationServiceFactory.class);
+
     private final DOMDataBroker dataBroker;
     private final CurrentSchemaContext currentSchemaContext;
 
@@ -32,4 +46,120 @@ public class MdsalNetconfOperationServiceFactory implements NetconfOperationServ
     public void close() throws Exception {
         currentSchemaContext.close();
     }
+
+    @Override
+    public Set<Capability> getCapabilities() {
+        final Set<Capability> capabilities = new HashSet<>();
+        // [RFC6241] 8.3.  Candidate Configuration Capability
+        capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+
+        final SchemaContext currentContext = currentSchemaContext.getCurrentContext();
+        final Set<Module> modules = currentContext.getModules();
+        for (final Module module : modules) {
+            if(currentContext.getModuleSource(module).isPresent()) {
+                capabilities.add(new YangStoreCapability(module, currentContext.getModuleSource(module).get()));
+            } else {
+                LOG.warn("Missing source for module {}. This module will not be available from netconf server",
+                        module);
+            }
+        }
+
+        return capabilities;
+    }
+
+    @Override
+    public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+        // TODO provide notifications about changed schemas
+        return new AutoCloseable() {
+            @Override
+            public void close() throws Exception {
+
+            }
+        };
+    }
+
+    private static class BasicCapability implements Capability {
+
+        private final String capability;
+
+        private BasicCapability(final String capability) {
+            this.capability = capability;
+        }
+
+        @Override
+        public String getCapabilityUri() {
+            return capability;
+        }
+
+        @Override
+        public Optional<String> getModuleNamespace() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getModuleName() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getRevision() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Optional<String> getCapabilitySchema() {
+            return Optional.absent();
+        }
+
+        @Override
+        public Collection<String> getLocation() {
+            return Collections.emptyList();
+        }
+
+        @Override
+        public String toString() {
+            return capability;
+        }
+    }
+
+    private static final class YangStoreCapability extends BasicCapability {
+
+        private final String content;
+        private final String revision;
+        private final String moduleName;
+        private final String moduleNamespace;
+
+        public YangStoreCapability(final Module module, final String moduleContent) {
+            super(toCapabilityURI(module));
+            this.content = moduleContent;
+            this.moduleName = module.getName();
+            this.moduleNamespace = module.getNamespace().toString();
+            this.revision = SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision());
+        }
+
+        @Override
+        public Optional<String> getCapabilitySchema() {
+            return Optional.of(content);
+        }
+
+        private static String toCapabilityURI(final Module module) {
+            return String.valueOf(module.getNamespace()) + "?module="
+                    + module.getName() + "&revision=" + SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision());
+        }
+
+        @Override
+        public Optional<String> getModuleName() {
+            return Optional.of(moduleName);
+        }
+
+        @Override
+        public Optional<String> getModuleNamespace() {
+            return Optional.of(moduleNamespace);
+        }
+
+        @Override
+        public Optional<String> getRevision() {
+            return Optional.of(revision);
+        }
+    }
 }
index e0c004461c116c5b1bb23f41c566537e565c05ef..8f6ff417d6499d47dc594bc5ab5fb2de03e937d0 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.netconf.mdsal.connector.ops.get;
 
 import com.google.common.base.Function;
+import com.google.common.base.Optional;
 import com.google.common.base.Throwables;
 import com.google.common.collect.Iterables;
 import java.io.IOException;
@@ -115,13 +116,13 @@ public abstract class AbstractGet extends AbstractLastNetconfOperation {
     }
 
     protected static final class GetConfigExecution {
-        private final Datastore datastore;
+        private final Optional<Datastore> datastore;
 
-        public GetConfigExecution(final Datastore datastore) {
+        public GetConfigExecution(final Optional<Datastore> datastore) {
             this.datastore = datastore;
         }
 
-        public Datastore getDatastore() {
+        public Optional<Datastore> getDatastore() {
             return datastore;
         }
 
@@ -132,7 +133,7 @@ public abstract class AbstractGet extends AbstractLastNetconfOperation {
                 throw new NetconfDocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
             }
 
-            final Datastore sourceDatastore;
+            final Optional<Datastore> sourceDatastore;
             try {
                 sourceDatastore = parseSource(xml);
             } catch (final NetconfDocumentedException e) {
@@ -144,14 +145,12 @@ public abstract class AbstractGet extends AbstractLastNetconfOperation {
             return new GetConfigExecution(sourceDatastore);
         }
 
-        private static Datastore parseSource(final XmlElement xml) throws NetconfDocumentedException {
-            final Datastore sourceDatastore;
-            final XmlElement sourceElement = xml.getOnlyChildElement(XmlNetconfConstants.SOURCE_KEY,
+        private static Optional<Datastore> parseSource(final XmlElement xml) throws NetconfDocumentedException {
+            final Optional<XmlElement> sourceElement = xml.getOnlyChildElementOptionally(XmlNetconfConstants.SOURCE_KEY,
                     XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
 
-            final String sourceParsed = sourceElement.getOnlyChildElement().getName();
-            sourceDatastore = Datastore.valueOf(sourceParsed);
-            return sourceDatastore;
+            return  sourceElement.isPresent() ?
+                    Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName())) : Optional.<Datastore>absent();
         }
 
         private static void validateInputRpc(final XmlElement xml, String operationName) throws NetconfDocumentedException{
index a2b2fbb0db0304184cdc653b34a1e5f046ee3267..cebd8c88837547f0f2d2f573ca0e2e81ed03e67a 100644 (file)
@@ -52,13 +52,10 @@ public class Get extends AbstractGet {
         }
 
         final YangInstanceIdentifier dataRoot = ROOT;
-        DOMDataReadWriteTransaction rwTx = getTransaction(getConfigExecution.getDatastore());
+        DOMDataReadWriteTransaction rwTx = getTransaction(Datastore.running);
         try {
             final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(LogicalDatastoreType.OPERATIONAL, dataRoot).checkedGet();
-            if (getConfigExecution.getDatastore() == Datastore.running) {
-                transactionProvider.abortRunningTransaction(rwTx);
-                rwTx = null;
-            }
+            transactionProvider.abortRunningTransaction(rwTx);
             return (Element) transformNormalizedNode(document, normalizedNodeOptional.get(), dataRoot);
         } catch (ReadFailedException e) {
             LOG.warn("Unable to read data: {}", dataRoot, e);
index b56bcc795caf3ad1c5adacaa98d445e1b63079a8..f2d8abbb6180f10785f7cb00c59dcb6d6fd7d5ee 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.netconf.mdsal.connector.ops.get;
 
 import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
@@ -52,10 +53,13 @@ public class GetConfig extends AbstractGet {
         }
 
         final YangInstanceIdentifier dataRoot = ROOT;
-        DOMDataReadWriteTransaction rwTx = getTransaction(getConfigExecution.getDatastore());
+        // Proper exception should be thrown
+        Preconditions.checkState(getConfigExecution.getDatastore().isPresent(), "Source element missing from request");
+
+        DOMDataReadWriteTransaction rwTx = getTransaction(getConfigExecution.getDatastore().get());
         try {
             final Optional<NormalizedNode<?, ?>> normalizedNodeOptional = rwTx.read(LogicalDatastoreType.CONFIGURATION, dataRoot).checkedGet();
-            if (getConfigExecution.getDatastore() == Datastore.running) {
+            if (getConfigExecution.getDatastore().get() == Datastore.running) {
                 transactionProvider.abortRunningTransaction(rwTx);
                 rwTx = null;
             }
similarity index 93%
rename from opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/Capability.java
rename to opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/Capability.java
index 408756bf4d221ac2eccde2cbb35133a7592e417f..6a061b1ea9056a5f153af79b4d0052ebb8f040a2 100644 (file)
@@ -6,7 +6,7 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.netconf.mapping.api;
+package org.opendaylight.controller.netconf.api;
 
 import com.google.common.base.Optional;
 import java.util.Collection;
diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/monitoring/CapabilityListener.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/monitoring/CapabilityListener.java
new file mode 100644 (file)
index 0000000..5d9468c
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2015 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.netconf.api.monitoring;
+
+import java.util.Set;
+import org.opendaylight.controller.netconf.api.Capability;
+
+public interface CapabilityListener {
+
+    void onCapabilitiesAdded(Set<Capability> addedCaps);
+
+    void onCapabilitiesRemoved(Set<Capability> removedCaps);
+}
index 51eea9307de4ff8b22188fe9385e8da242e0544b..3f0e1a1aa58b795ec501d1e0790da041306aa384 100644 (file)
@@ -7,12 +7,19 @@
  */
 package org.opendaylight.controller.netconf.api.monitoring;
 
+import com.google.common.base.Optional;
+import java.util.Set;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Sessions;
 
-public interface NetconfMonitoringService {
+public interface NetconfMonitoringService extends CapabilityListener, SessionListener {
 
     Sessions getSessions();
 
     Schemas getSchemas();
+
+    String getSchemaForCapability(String moduleName, Optional<String> revision);
+
+    Set<String> getCapabilities();
+
 }
@@ -1,16 +1,17 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2015 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.netconf.impl.osgi;
 
-import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
-
-public interface SessionMonitoringService {
+package org.opendaylight.controller.netconf.api.monitoring;
 
+/**
+ * Created by mmarsale on 13.2.2015.
+ */
+public interface SessionListener {
     void onSessionUp(NetconfManagementSession session);
 
     void onSessionDown(NetconfManagementSession session);
index f775da91c0456cb49d1043291feba48e2f815855..e2b0d35867832ddb87bb3c1833fada6cfcf1554c 100644 (file)
@@ -19,4 +19,9 @@ module netconf-northbound {
         config:java-class "org.opendaylight.controller.netconf.api.NetconfServerDispatcher";
     }
 
+    identity netconf-server-monitoring {
+        base "config:service-type";
+        config:java-class "org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService";
+    }
+
 }
\ No newline at end of file
index e64620d4ad42247ddcad43913dbefebd3b6c5bf1..c1570f4311f67f9b7badfb609e30f55144e308bc 100644 (file)
@@ -1,13 +1,13 @@
 package org.opendaylight.controller.config.yang.config.netconf.northbound.impl;
 
 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.impl.CommitNotifier;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 
 public class NetconfServerDispatcherModule extends org.opendaylight.controller.config.yang.config.netconf.northbound.impl.AbstractNetconfServerDispatcherModule {
@@ -27,8 +27,8 @@ public class NetconfServerDispatcherModule extends org.opendaylight.controller.c
     @Override
     public java.lang.AutoCloseable createInstance() {
 
-        final NetconfOperationServiceFactoryListenerImpl aggregatedOpProvider = getAggregatedOpProvider();
-        final SessionMonitoringService monitoringService = startMonitoringService(aggregatedOpProvider);
+        final AggregatedNetconfOperationServiceFactory aggregatedOpProvider = getAggregatedOpProvider();
+        final NetconfMonitoringService monitoringService = startMonitoringService(aggregatedOpProvider);
         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
                 getTimerDependency(), aggregatedOpProvider, new SessionIdProvider(), getConnectionTimeoutMillis(), CommitNotifier.NoopCommitNotifier.getInstance(), monitoringService);
         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
@@ -44,12 +44,12 @@ public class NetconfServerDispatcherModule extends org.opendaylight.controller.c
 
     }
 
-    private NetconfMonitoringServiceImpl startMonitoringService(final NetconfOperationServiceFactoryListenerImpl netconfOperationProvider) {
+    private NetconfMonitoringServiceImpl startMonitoringService(final AggregatedNetconfOperationServiceFactory netconfOperationProvider) {
         return new NetconfMonitoringServiceImpl(netconfOperationProvider);
     }
 
-    private NetconfOperationServiceFactoryListenerImpl getAggregatedOpProvider() {
-        final NetconfOperationServiceFactoryListenerImpl netconfOperationProvider = new NetconfOperationServiceFactoryListenerImpl();
+    private AggregatedNetconfOperationServiceFactory getAggregatedOpProvider() {
+        final AggregatedNetconfOperationServiceFactory netconfOperationProvider = new AggregatedNetconfOperationServiceFactory();
         for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getMappersDependency()) {
             netconfOperationProvider.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
         }
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/CapabilityProviderImpl.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/CapabilityProviderImpl.java
deleted file mode 100644 (file)
index 13cc973..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CapabilityProviderImpl implements CapabilityProvider {
-    private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
-    private final Set<String> capabilityURIs;
-
-    private static final Logger LOG = LoggerFactory.getLogger(CapabilityProviderImpl.class);
-
-    public CapabilityProviderImpl(NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
-        this.netconfOperationServiceSnapshot = netconfOperationServiceSnapshot;
-        Map<String, Capability> urisToCapabilitiesInternalMap = getCapabilitiesInternal(netconfOperationServiceSnapshot);
-        List<String> capabilityURIs = new ArrayList<>(urisToCapabilitiesInternalMap.keySet());
-        Collections.sort(capabilityURIs);
-        this.capabilityURIs = Collections.unmodifiableSet(new TreeSet<>(capabilityURIs));
-    }
-
-    private static Map<String, Capability> getCapabilitiesInternal(
-            NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
-        Map<String, Capability> capabilityMap = Maps.newHashMap();
-
-        for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
-            final Set<Capability> caps = netconfOperationService.getCapabilities();
-
-            for (Capability cap : caps) {
-
-                if(capabilityMap.containsKey(cap.getCapabilityUri())) {
-                    LOG.debug("Duplicate capability {} from service {}", cap.getCapabilityUri(), netconfOperationService);
-                }
-
-                capabilityMap.put(cap.getCapabilityUri(), cap);
-            }
-        }
-
-        return capabilityMap;
-    }
-
-    @Override
-    public synchronized String getSchemaForCapability(String moduleName, Optional<String> revision) {
-
-        Map<String, Map<String, String>> mappedModulesToRevisionToSchema = Maps.newHashMap();
-
-        for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
-            final Set<Capability> caps = netconfOperationService.getCapabilities();
-
-            for (Capability cap : caps) {
-                if (!cap.getModuleName().isPresent()
-                        || !cap.getRevision().isPresent()
-                        || !cap.getCapabilitySchema().isPresent()){
-                    continue;
-                }
-
-                final String currentModuleName = cap.getModuleName().get();
-                Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
-                if (revisionMap == null) {
-                    revisionMap = Maps.newHashMap();
-                    mappedModulesToRevisionToSchema.put(currentModuleName, revisionMap);
-                }
-
-                String currentRevision = cap.getRevision().get();
-                revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
-            }
-        }
-
-        Map<String, String> revisionMapRequest = mappedModulesToRevisionToSchema.get(moduleName);
-        Preconditions.checkState(revisionMapRequest != null, "Capability for module %s not present, " + ""
-                + "available modules : %s", moduleName, capabilityURIs);
-
-        if (revision.isPresent()) {
-            String schema = revisionMapRequest.get(revision.get());
-
-            Preconditions.checkState(schema != null,
-                    "Capability for module %s:%s not present, available revisions for module: %s", moduleName,
-                    revision.get(), revisionMapRequest.keySet());
-
-            return schema;
-        } else {
-            Preconditions.checkState(revisionMapRequest.size() == 1,
-                    "Expected 1 capability for module %s, available revisions : %s", moduleName,
-                    revisionMapRequest.keySet());
-            return revisionMapRequest.values().iterator().next();
-        }
-    }
-
-    @Override
-    public synchronized Set<String> getCapabilities() {
-        return capabilityURIs;
-    }
-
-}
index 951d0dd98d7d2b52bb13e6fc21a8f88673c74de6..9510a61a6edd0a234ea9ee1fc5237c144fdd59ec 100644 (file)
@@ -15,10 +15,10 @@ import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
 import org.opendaylight.controller.netconf.util.messages.SendErrorExceptionUtil;
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
@@ -31,11 +31,11 @@ import org.w3c.dom.Node;
 public class NetconfServerSessionListener implements NetconfSessionListener<NetconfServerSession> {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionListener.class);
-    private final SessionMonitoringService monitoringService;
+    private final NetconfMonitoringService monitoringService;
     private final NetconfOperationRouter operationRouter;
     private final AutoCloseable onSessionDownCloseable;
 
-    public NetconfServerSessionListener(final NetconfOperationRouter operationRouter, final SessionMonitoringService monitoringService,
+    public NetconfServerSessionListener(final NetconfOperationRouter operationRouter, NetconfMonitoringService monitoringService,
                                         final AutoCloseable onSessionDownCloseable) {
         this.operationRouter = operationRouter;
         this.monitoringService = monitoringService;
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionListenerFactory.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionListenerFactory.java
deleted file mode 100644 (file)
index 604cc5f..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl;
-
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouterImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
-import org.opendaylight.protocol.framework.SessionListenerFactory;
-
-public class NetconfServerSessionListenerFactory implements SessionListenerFactory<NetconfServerSessionListener> {
-
-    private final CommitNotifier commitNotifier;
-    private final SessionMonitoringService monitor;
-    private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
-    private final CapabilityProvider capabilityProvider;
-
-    public NetconfServerSessionListenerFactory(final CommitNotifier commitNotifier,
-                                               final SessionMonitoringService monitor,
-                                               final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot,
-                                               final CapabilityProvider capabilityProvider) {
-
-        this.commitNotifier = commitNotifier;
-        this.monitor = monitor;
-        this.netconfOperationServiceSnapshot = netconfOperationServiceSnapshot;
-        this.capabilityProvider = capabilityProvider;
-    }
-
-    @Override
-    public NetconfServerSessionListener getSessionListener() {
-        NetconfOperationRouter operationRouter = new NetconfOperationRouterImpl(netconfOperationServiceSnapshot, capabilityProvider, commitNotifier);
-        return new NetconfServerSessionListener(operationRouter, monitor, netconfOperationServiceSnapshot);
-    }
-}
index 451c066b772f5d705c0904fadd183ef48926a683..996bb275877dd74f336db4a410e765fb12f25424 100644 (file)
@@ -8,8 +8,6 @@
 
 package org.opendaylight.controller.netconf.impl;
 
-import static org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider.NetconfOperationProviderUtil.getNetconfSessionIdForReporting;
-
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
@@ -19,11 +17,12 @@ import io.netty.util.concurrent.Promise;
 import java.util.Set;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouterImpl;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
 import org.opendaylight.protocol.framework.SessionListenerFactory;
 import org.opendaylight.protocol.framework.SessionNegotiator;
@@ -42,28 +41,28 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
     private final Timer timer;
 
     private final SessionIdProvider idProvider;
-    private final NetconfOperationProvider netconfOperationProvider;
+    private final NetconfOperationServiceFactory aggregatedOpService;
     private final long connectionTimeoutMillis;
     private final CommitNotifier commitNotificationProducer;
-    private final SessionMonitoringService monitoringService;
+    private final NetconfMonitoringService monitoringService;
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
     private final Set<String> baseCapabilities;
 
     // TODO too many params, refactor
-    public NetconfServerSessionNegotiatorFactory(Timer timer, NetconfOperationProvider netconfOperationProvider,
-                                                 SessionIdProvider idProvider, long connectionTimeoutMillis,
-                                                 CommitNotifier commitNot,
-                                                 SessionMonitoringService monitoringService) {
+    public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
+                                                 final SessionIdProvider idProvider, final long connectionTimeoutMillis,
+                                                 final CommitNotifier commitNot,
+                                                 final NetconfMonitoringService monitoringService) {
         this(timer, netconfOperationProvider, idProvider, connectionTimeoutMillis, commitNot, monitoringService, DEFAULT_BASE_CAPABILITIES);
     }
 
     // TODO too many params, refactor
-    public NetconfServerSessionNegotiatorFactory(Timer timer, NetconfOperationProvider netconfOperationProvider,
-                                                 SessionIdProvider idProvider, long connectionTimeoutMillis,
-                                                 CommitNotifier commitNot,
-                                                 SessionMonitoringService monitoringService, Set<String> baseCapabilities) {
+    public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
+                                                 final SessionIdProvider idProvider, final long connectionTimeoutMillis,
+                                                 final CommitNotifier commitNot,
+                                                 final NetconfMonitoringService monitoringService, final Set<String> baseCapabilities) {
         this.timer = timer;
-        this.netconfOperationProvider = netconfOperationProvider;
+        this.aggregatedOpService = netconfOperationProvider;
         this.idProvider = idProvider;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
         this.commitNotificationProducer = commitNot;
@@ -73,12 +72,12 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
 
     private ImmutableSet<String> validateBaseCapabilities(final Set<String> baseCapabilities) {
         // Check base capabilities to be supported by the server
-        Sets.SetView<String> unknownBaseCaps = Sets.difference(baseCapabilities, DEFAULT_BASE_CAPABILITIES);
+        final Sets.SetView<String> unknownBaseCaps = Sets.difference(baseCapabilities, DEFAULT_BASE_CAPABILITIES);
         Preconditions.checkArgument(unknownBaseCaps.isEmpty(),
                 "Base capabilities that will be supported by netconf server have to be subset of %s, unknown base capabilities: %s",
                 DEFAULT_BASE_CAPABILITIES, unknownBaseCaps);
 
-        ImmutableSet.Builder<String> b = ImmutableSet.builder();
+        final ImmutableSet.Builder<String> b = ImmutableSet.builder();
         b.addAll(baseCapabilities);
         // Base 1.0 capability is supported by default
         b.add(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0);
@@ -95,31 +94,32 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
      * @return session negotiator
      */
     @Override
-    public SessionNegotiator<NetconfServerSession> getSessionNegotiator(SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
-                                                                        Channel channel, Promise<NetconfServerSession> promise) {
-        long sessionId = idProvider.getNextSessionId();
-        NetconfOperationServiceSnapshot netconfOperationServiceSnapshot = netconfOperationProvider.openSnapshot(
-                getNetconfSessionIdForReporting(sessionId));
-        CapabilityProvider capabilityProvider = new CapabilityProviderImpl(netconfOperationServiceSnapshot);
-
-        NetconfServerSessionPreferences proposal = null;
+    public SessionNegotiator<NetconfServerSession> getSessionNegotiator(final SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
+                                                                        final Channel channel, final Promise<NetconfServerSession> promise) {
+        final long sessionId = idProvider.getNextSessionId();
+
+        NetconfServerSessionPreferences proposal;
         try {
-            proposal = new NetconfServerSessionPreferences(
-                    createHelloMessage(sessionId, capabilityProvider), sessionId);
-        } catch (NetconfDocumentedException e) {
-            LOG.error("Unable to create hello mesage for session {} with capability provider {}", sessionId,capabilityProvider);
+            proposal = new NetconfServerSessionPreferences(createHelloMessage(sessionId, monitoringService), sessionId);
+        } catch (final NetconfDocumentedException e) {
+            LOG.error("Unable to create hello message for session {} with {}", sessionId, monitoringService);
             throw new IllegalStateException(e);
         }
 
-        NetconfServerSessionListenerFactory sessionListenerFactory = new NetconfServerSessionListenerFactory(
-                commitNotificationProducer, monitoringService,
-                netconfOperationServiceSnapshot, capabilityProvider);
-
         return new NetconfServerSessionNegotiator(proposal, promise, channel, timer,
-                sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
+                getListener(Long.toString(sessionId)), connectionTimeoutMillis);
+    }
+
+    private NetconfServerSessionListener getListener(final String netconfSessionIdForReporting) {
+        final NetconfOperationService service =
+                this.aggregatedOpService.createService(netconfSessionIdForReporting);
+        final NetconfOperationRouter operationRouter =
+                new NetconfOperationRouterImpl(service, commitNotificationProducer, monitoringService, netconfSessionIdForReporting);
+        return new NetconfServerSessionListener(operationRouter, monitoringService, service);
+
     }
 
-    private NetconfHelloMessage createHelloMessage(long sessionId, CapabilityProvider capabilityProvider) throws NetconfDocumentedException {
+    private NetconfHelloMessage createHelloMessage(final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
         return NetconfHelloMessage.createServerHello(Sets.union(capabilityProvider.getCapabilities(), baseCapabilities), sessionId);
     }
 
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/CapabilityProvider.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/CapabilityProvider.java
deleted file mode 100644 (file)
index 60cde27..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl.mapping;
-
-import com.google.common.base.Optional;
-import java.util.Set;
-
-public interface CapabilityProvider {
-
-    String getSchemaForCapability(String moduleName, Optional<String> revision);
-
-    Set<String> getCapabilities();
-
-}
index 742255f973ca4eaebf79958e4c67d251e3a1b922..ca41338c36e523fcd1a84f7d15cb157d1c53eeb0 100644 (file)
@@ -11,9 +11,9 @@ package org.opendaylight.controller.netconf.impl.mapping.operations;
 import com.google.common.base.Preconditions;
 import java.io.InputStream;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.impl.CommitNotifier;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -32,10 +32,10 @@ public class DefaultCommit extends AbstractNetconfOperation {
     private static final String NOTIFY_ATTR = "notify";
 
     private final CommitNotifier notificationProducer;
-    private final CapabilityProvider cap;
+    private final NetconfMonitoringService cap;
     private final NetconfOperationRouter operationRouter;
 
-    public DefaultCommit(CommitNotifier notifier, CapabilityProvider cap,
+    public DefaultCommit(CommitNotifier notifier, NetconfMonitoringService cap,
                          String netconfSessionIdForReporting, NetconfOperationRouter netconfOperationRouter) {
         super(netconfSessionIdForReporting);
         this.notificationProducer = notifier;
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/AggregatedNetconfOperationServiceFactory.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/AggregatedNetconfOperationServiceFactory.java
new file mode 100644 (file)
index 0000000..c299ac7
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.netconf.impl.osgi;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Sets;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.controller.netconf.util.CloseableUtil;
+
+/**
+ * NetconfOperationService aggregator. Makes a collection of operation services accessible as one.
+ */
+public class AggregatedNetconfOperationServiceFactory implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener {
+
+    private final Set<NetconfOperationServiceFactory> factories = new HashSet<>();
+    private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations = HashMultimap.create();
+    private final Set<CapabilityListener> listeners = Sets.newHashSet();
+
+    @Override
+    public synchronized void onAddNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
+        factories.add(service);
+
+        for (final CapabilityListener listener : listeners) {
+            AutoCloseable reg = service.registerCapabilityListener(listener);
+            registrations.put(service, reg);
+        }
+    }
+
+    @Override
+    public synchronized void onRemoveNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
+        factories.remove(service);
+
+        for (final AutoCloseable autoCloseable : registrations.get(service)) {
+            try {
+                autoCloseable.close();
+            } catch (Exception e) {
+                // FIXME Issue warning
+            }
+        }
+
+        registrations.removeAll(service);
+    }
+
+    @Override
+    public synchronized Set<Capability> getCapabilities() {
+        final HashSet<Capability> capabilities = Sets.newHashSet();
+        for (final NetconfOperationServiceFactory factory : factories) {
+            capabilities.addAll(factory.getCapabilities());
+        }
+        return capabilities;
+    }
+
+    @Override
+    public synchronized AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+        final Map<NetconfOperationServiceFactory, AutoCloseable> regs = Maps.newHashMap();
+
+        for (final NetconfOperationServiceFactory factory : factories) {
+            final AutoCloseable reg = factory.registerCapabilityListener(listener);
+            regs.put(factory, reg);
+        }
+        listeners.add(listener);
+
+        return new AutoCloseable() {
+            @Override
+            public void close() throws Exception {
+                synchronized (AggregatedNetconfOperationServiceFactory.this) {
+                    listeners.remove(listener);
+                    CloseableUtil.closeAll(regs.values());
+                    for (final Map.Entry<NetconfOperationServiceFactory, AutoCloseable> reg : regs.entrySet()) {
+                        registrations.remove(reg.getKey(), reg.getValue());
+                    }
+                }
+            }
+        };
+    }
+
+    @Override
+    public synchronized NetconfOperationService createService(final String netconfSessionIdForReporting) {
+        return new AggregatedNetconfOperation(factories, netconfSessionIdForReporting);
+    }
+
+    private static final class AggregatedNetconfOperation implements NetconfOperationService {
+
+        private final Set<NetconfOperationService> services;
+
+        public AggregatedNetconfOperation(final Set<NetconfOperationServiceFactory> factories, final String netconfSessionIdForReporting) {
+            final Builder<NetconfOperationService> b = ImmutableSet.builder();
+            for (final NetconfOperationServiceFactory factory : factories) {
+                b.add(factory.createService(netconfSessionIdForReporting));
+            }
+            this.services = b.build();
+        }
+
+        @Override
+        public Set<NetconfOperation> getNetconfOperations() {
+            final HashSet<NetconfOperation> operations = Sets.newHashSet();
+            for (final NetconfOperationService service : services) {
+                operations.addAll(service.getNetconfOperations());
+            }
+            return operations;
+        }
+
+        @Override
+        public void close() {
+            try {
+                CloseableUtil.closeAll(services);
+            } catch (final Exception e) {
+                throw new IllegalStateException("Unable to properly close all aggregated services", e);
+            }
+        }
+    }
+}
index a55e32a954ad99a85521e11f541567c962a20b84..63e837fc18d5c97b4de8f31692b9b5d6c6cc29bf 100644 (file)
@@ -19,7 +19,6 @@ import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProduce
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
@@ -40,7 +39,7 @@ public class NetconfImplActivator implements BundleActivator {
     @Override
     public void start(final BundleContext context)  {
 
-        NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
+        AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
         startOperationServiceFactoryTracker(context, factoriesListener);
 
         SessionIdProvider idProvider = new SessionIdProvider();
@@ -50,7 +49,7 @@ public class NetconfImplActivator implements BundleActivator {
 
         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
-        SessionMonitoringService monitoringService = startMonitoringService(context, factoriesListener);
+        NetconfMonitoringService monitoringService = startMonitoringService(context, factoriesListener);
 
         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
                 timer, factoriesListener, idProvider, connectionTimeoutMillis, commitNot, monitoringService);
@@ -64,17 +63,14 @@ public class NetconfImplActivator implements BundleActivator {
         LocalAddress address = NetconfConfigUtil.getNetconfLocalAddress();
         LOG.trace("Starting local netconf server at {}", address);
         dispatch.createLocalServer(address);
-
-        context.registerService(NetconfOperationProvider.class, factoriesListener, null);
-
     }
 
-    private void startOperationServiceFactoryTracker(BundleContext context, NetconfOperationServiceFactoryListenerImpl factoriesListener) {
+    private void startOperationServiceFactoryTracker(BundleContext context, NetconfOperationServiceFactoryListener factoriesListener) {
         factoriesTracker = new NetconfOperationServiceFactoryTracker(context, factoriesListener);
         factoriesTracker.open();
     }
 
-    private NetconfMonitoringServiceImpl startMonitoringService(BundleContext context, NetconfOperationServiceFactoryListenerImpl factoriesListener) {
+    private NetconfMonitoringServiceImpl startMonitoringService(BundleContext context, AggregatedNetconfOperationServiceFactory factoriesListener) {
         NetconfMonitoringServiceImpl netconfMonitoringServiceImpl = new NetconfMonitoringServiceImpl(factoriesListener);
         Dictionary<String, ?> dic = new Hashtable<>();
         regMonitoring = context.registerService(NetconfMonitoringService.class, netconfMonitoringServiceImpl, dic);
index efbe3ad68fe4615334c08206054cc755e20ff87b..8e5c1a7da3e1b947f1de1429f11bddcc81fb6cb6 100644 (file)
@@ -8,23 +8,24 @@
 package org.opendaylight.controller.netconf.impl.osgi;
 
 import com.google.common.base.Function;
+import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.Maps;
 import io.netty.util.internal.ConcurrentSet;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import javax.annotation.Nonnull;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
@@ -38,7 +39,8 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, SessionMonitoringService {
+public class NetconfMonitoringServiceImpl implements NetconfMonitoringService {
+
     private static final Schema.Location NETCONF_LOCATION = new Schema.Location(Schema.Location.Enumeration.NETCONF);
     private static final List<Schema.Location> NETCONF_LOCATIONS = ImmutableList.of(NETCONF_LOCATION);
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceImpl.class);
@@ -50,10 +52,20 @@ public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, S
     };
 
     private final Set<NetconfManagementSession> sessions = new ConcurrentSet<>();
-    private final NetconfOperationProvider netconfOperationProvider;
+    private final NetconfOperationServiceFactory netconfOperationProvider;
+    private final Map<String, Capability> capabilities = new ConcurrentHashMap<>();
+    private static final Function<Capability, String> CAPABILITY_TO_URI = new Function<Capability, String>() {
+        @Override
+        public String apply(final Capability input) {
+            return input.getCapabilityUri();
+        }
+    };
 
-    public NetconfMonitoringServiceImpl(final NetconfOperationProvider netconfOperationProvider) {
+    // FIXME check threadsafety
+
+    public NetconfMonitoringServiceImpl(final NetconfOperationServiceFactory netconfOperationProvider) {
         this.netconfOperationProvider = netconfOperationProvider;
+        netconfOperationProvider.registerCapabilityListener(this);
     }
 
     @Override
@@ -77,38 +89,81 @@ public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, S
 
     @Override
     public Schemas getSchemas() {
-        // capabilities should be split from operations (it will allow to move getSchema operation to monitoring module)
-        try (NetconfOperationServiceSnapshot snapshot = netconfOperationProvider.openSnapshot("netconf-monitoring")) {
-            return transformSchemas(snapshot.getServices());
-        } catch (RuntimeException e) {
+        try {
+            return transformSchemas(netconfOperationProvider.getCapabilities());
+        } catch (final RuntimeException e) {
             throw e;
-        } catch (Exception e) {
+        } catch (final Exception e) {
             throw new IllegalStateException("Exception while closing", e);
         }
     }
 
-    private static Schemas transformSchemas(final Set<NetconfOperationService> services) {
-        // FIXME: Capability implementations do not have hashcode/equals!
-        final Set<Capability> caps = new HashSet<>();
-        for (NetconfOperationService netconfOperationService : services) {
-            // TODO check for duplicates ? move capability merging to snapshot
-            // Split capabilities from operations first and delete this duplicate code
-            caps.addAll(netconfOperationService.getCapabilities());
+    @Override
+    public String getSchemaForCapability(final String moduleName, final Optional<String> revision) {
+
+        // FIXME not effective at all
+
+        Map<String, Map<String, String>> mappedModulesToRevisionToSchema = Maps.newHashMap();
+
+        final Collection<Capability> caps = capabilities.values();
+
+        for (Capability cap : caps) {
+            if (!cap.getModuleName().isPresent()
+                    || !cap.getRevision().isPresent()
+                    || !cap.getCapabilitySchema().isPresent()){
+                continue;
+            }
+
+            final String currentModuleName = cap.getModuleName().get();
+            Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
+            if (revisionMap == null) {
+                revisionMap = Maps.newHashMap();
+                mappedModulesToRevisionToSchema.put(currentModuleName, revisionMap);
+            }
+
+            String currentRevision = cap.getRevision().get();
+            revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
+        }
+
+        Map<String, String> revisionMapRequest = mappedModulesToRevisionToSchema.get(moduleName);
+        Preconditions.checkState(revisionMapRequest != null, "Capability for module %s not present, " + ""
+                + "available modules : %s", moduleName, Collections2.transform(caps, CAPABILITY_TO_URI));
+
+        if (revision.isPresent()) {
+            String schema = revisionMapRequest.get(revision.get());
+
+            Preconditions.checkState(schema != null,
+                    "Capability for module %s:%s not present, available revisions for module: %s", moduleName,
+                    revision.get(), revisionMapRequest.keySet());
+
+            return schema;
+        } else {
+            Preconditions.checkState(revisionMapRequest.size() == 1,
+                    "Expected 1 capability for module %s, available revisions : %s", moduleName,
+                    revisionMapRequest.keySet());
+            return revisionMapRequest.values().iterator().next();
         }
+    }
+
+    @Override
+    public Set<String> getCapabilities() {
+        return capabilities.keySet();
+    }
 
+    private static Schemas transformSchemas(final Set<Capability> caps) {
         final List<Schema> schemas = new ArrayList<>(caps.size());
-        for (Capability cap : caps) {
+        for (final Capability cap : caps) {
             if (cap.getCapabilitySchema().isPresent()) {
-                SchemaBuilder builder = new SchemaBuilder();
+                final SchemaBuilder builder = new SchemaBuilder();
                 Preconditions.checkState(cap.getModuleNamespace().isPresent());
                 builder.setNamespace(new Uri(cap.getModuleNamespace().get()));
 
                 Preconditions.checkState(cap.getRevision().isPresent());
-                String version = cap.getRevision().get();
+                final String version = cap.getRevision().get();
                 builder.setVersion(version);
 
                 Preconditions.checkState(cap.getModuleName().isPresent());
-                String identifier = cap.getModuleName().get();
+                final String identifier = cap.getModuleName().get();
                 builder.setIdentifier(identifier);
 
                 builder.setFormat(Yang.class);
@@ -132,10 +187,23 @@ public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, S
         final Builder<Schema.Location> b = ImmutableList.builder();
         b.add(NETCONF_LOCATION);
 
-        for (String location : locations) {
+        for (final String location : locations) {
             b.add(new Schema.Location(new Uri(location)));
         }
 
         return b.build();
     }
+
+    @Override
+    public void onCapabilitiesAdded(final Set<Capability> addedCaps) {
+        // FIXME what check for duplicates
+        this.capabilities.putAll(Maps.uniqueIndex(addedCaps, CAPABILITY_TO_URI));
+    }
+
+    @Override
+    public void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
+        for (final Capability addedCap : addedCaps) {
+            capabilities.remove(addedCap.getCapabilityUri());
+        }
+    }
 }
index c8fa3417473219cc284e5a7891726c52c58ad344..fb5a2b325efb1301befb8bb7882644d7dd25d131 100644 (file)
@@ -17,12 +17,11 @@ import java.util.NavigableMap;
 import java.util.Set;
 import java.util.TreeMap;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.impl.CommitNotifier;
 import org.opendaylight.controller.netconf.impl.NetconfServerSession;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
-import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultGetSchema;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultNetconfOperation;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStartExi;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStopExi;
@@ -30,7 +29,6 @@ import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
 import org.opendaylight.controller.netconf.mapping.api.SessionAwareNetconfOperation;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.slf4j.Logger;
@@ -40,29 +38,20 @@ import org.w3c.dom.Document;
 public class NetconfOperationRouterImpl implements NetconfOperationRouter {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfOperationRouterImpl.class);
-    private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
+    private final NetconfOperationService netconfOperationServiceSnapshot;
     private final Collection<NetconfOperation> allNetconfOperations;
 
-    public NetconfOperationRouterImpl(final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot, final CapabilityProvider capabilityProvider,
-            final CommitNotifier commitNotifier) {
+    public NetconfOperationRouterImpl(final NetconfOperationService netconfOperationServiceSnapshot,
+                                      final CommitNotifier commitNotifier, final NetconfMonitoringService netconfMonitoringService, final String sessionId) {
         this.netconfOperationServiceSnapshot = Preconditions.checkNotNull(netconfOperationServiceSnapshot);
 
-        final String sessionId = netconfOperationServiceSnapshot.getNetconfSessionIdForReporting();
-
         final Set<NetconfOperation> ops = new HashSet<>();
-        ops.add(new DefaultGetSchema(capabilityProvider, sessionId));
         ops.add(new DefaultCloseSession(sessionId, this));
         ops.add(new DefaultStartExi(sessionId));
         ops.add(new DefaultStopExi(sessionId));
-        ops.add(new DefaultCommit(commitNotifier, capabilityProvider, sessionId, this));
+        ops.add(new DefaultCommit(commitNotifier, netconfMonitoringService, sessionId, this));
 
-        for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
-            for (NetconfOperation netconfOperation : netconfOperationService.getNetconfOperations()) {
-                Preconditions.checkState(!ops.contains(netconfOperation),
-                        "Netconf operation %s already present", netconfOperation);
-                ops.add(netconfOperation);
-            }
-        }
+        ops.addAll(netconfOperationServiceSnapshot.getNetconfOperations());
 
         allNetconfOperations = ImmutableSet.copyOf(ops);
     }
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryListenerImpl.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryListenerImpl.java
deleted file mode 100644 (file)
index 6c55c35..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.impl.osgi;
-
-import java.util.HashSet;
-import java.util.Set;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-
-public class NetconfOperationServiceFactoryListenerImpl implements NetconfOperationServiceFactoryListener,
-        NetconfOperationProvider {
-    private final Set<NetconfOperationServiceFactory> allFactories = new HashSet<>();
-
-    @Override
-    public synchronized void onAddNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
-        allFactories.add(service);
-    }
-
-    @Override
-    public synchronized void onRemoveNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
-        allFactories.remove(service);
-    }
-
-    @Override
-    public synchronized NetconfOperationServiceSnapshotImpl openSnapshot(String sessionIdForReporting) {
-        return new NetconfOperationServiceSnapshotImpl(allFactories, sessionIdForReporting);
-    }
-
-}
diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceSnapshotImpl.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceSnapshotImpl.java
deleted file mode 100644 (file)
index 26abdd9..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl.osgi;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSet.Builder;
-import java.util.Set;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
-import org.opendaylight.controller.netconf.util.CloseableUtil;
-
-public class NetconfOperationServiceSnapshotImpl implements NetconfOperationServiceSnapshot {
-
-    private final Set<NetconfOperationService> services;
-    private final String netconfSessionIdForReporting;
-
-    public NetconfOperationServiceSnapshotImpl(final Set<NetconfOperationServiceFactory> factories, final String sessionIdForReporting) {
-        final Builder<NetconfOperationService> b = ImmutableSet.builder();
-        netconfSessionIdForReporting = sessionIdForReporting;
-        for (NetconfOperationServiceFactory factory : factories) {
-            b.add(factory.createService(netconfSessionIdForReporting));
-        }
-        this.services = b.build();
-    }
-
-    @Override
-    public String getNetconfSessionIdForReporting() {
-        return netconfSessionIdForReporting;
-    }
-
-    @Override
-    public Set<NetconfOperationService> getServices() {
-        return services;
-    }
-
-    @Override
-    public void close() throws Exception {
-        CloseableUtil.closeAll(services);
-    }
-
-    @Override
-    public String toString() {
-        return "NetconfOperationServiceSnapshotImpl{" + netconfSessionIdForReporting + '}';
-    }
-}
index 8e8a73b914cdf79ca7ad7e24d98ab31a859b0f44..36dfb6f31baf16892b2f556fee707892a86ee4f6 100644 (file)
@@ -13,6 +13,7 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
 import com.google.common.base.Preconditions;
@@ -48,8 +49,11 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
@@ -57,9 +61,7 @@ import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionList
 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -115,10 +117,11 @@ public class ConcurrentClientsTest {
     HashedWheelTimer hashedWheelTimer;
     private TestingNetconfOperation testingNetconfOperation;
 
-    public static SessionMonitoringService createMockedMonitoringService() {
-        SessionMonitoringService monitoring = mock(SessionMonitoringService.class);
+    public static NetconfMonitoringService createMockedMonitoringService() {
+        NetconfMonitoringService monitoring = mock(NetconfMonitoringService.class);
         doNothing().when(monitoring).onSessionUp(any(NetconfServerSession.class));
         doNothing().when(monitoring).onSessionDown(any(NetconfServerSession.class));
+        doReturn(Collections.emptySet()).when(monitoring).getCapabilities();
         return monitoring;
     }
 
@@ -143,7 +146,7 @@ public class ConcurrentClientsTest {
         nettyGroup = new NioEventLoopGroup(nettyThreads);
         netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
 
-        NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
+        AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
 
         testingNetconfOperation = new TestingNetconfOperation();
         factoriesListener.onAddNetconfOperationServiceFactory(new TestingOperationServiceFactory(testingNetconfOperation));
@@ -259,13 +262,22 @@ public class ConcurrentClientsTest {
             this.operations = operations;
         }
 
+        @Override
+        public Set<Capability> getCapabilities() {
+            return Collections.emptySet();
+        }
+
+        @Override
+        public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+            return new AutoCloseable(){
+                @Override
+                public void close() throws Exception {}
+            };
+        }
+
         @Override
         public NetconfOperationService createService(String netconfSessionIdForReporting) {
             return new NetconfOperationService() {
-                @Override
-                public Set<Capability> getCapabilities() {
-                    return Collections.emptySet();
-                }
 
                 @Override
                 public Set<NetconfOperation> getNetconfOperations() {
index df4069ac17f1a37bb81833c067bc9d46488825bc..4fd04e29ef178148ced11c1e0fdd2e252703fd4a 100644 (file)
@@ -17,7 +17,7 @@ import java.net.InetSocketAddress;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 
 public class NetconfDispatcherImplTest {
 
@@ -33,7 +33,7 @@ public class NetconfDispatcherImplTest {
 
         commitNot = new DefaultCommitNotificationProducer(
                 ManagementFactory.getPlatformMBeanServer());
-        NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
+        AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
 
         SessionIdProvider idProvider = new SessionIdProvider();
         hashedWheelTimer = new HashedWheelTimer();
index 93caa09286435f627638259784100d85ab203450..fed4742dd851d1a51a7e41a61e55355dc08a64d4 100644 (file)
@@ -8,107 +8,7 @@
 
 package org.opendaylight.controller.netconf.impl;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import io.netty.channel.Channel;
-import java.util.Set;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
-import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
-
 public class NetconfMonitoringServiceImplTest {
 
-    private NetconfMonitoringServiceImpl service;
-
-    @Mock
-    private NetconfOperationProvider operationProvider;
-    @Mock
-    private NetconfManagementSession managementSession;
-    @Mock
-    private NetconfOperationServiceSnapshot snapshot;
-    @Mock
-    private NetconfOperationService operationService;
-
-    @Before
-    public void setUp() throws Exception {
-        MockitoAnnotations.initMocks(this);
-        service = new NetconfMonitoringServiceImpl(operationProvider);
-    }
-
-    @Test
-    public void testSessions() throws Exception {
-        doReturn("sessToStr").when(managementSession).toString();
-        service.onSessionUp(managementSession);
-    }
-
-    @Test(expected = RuntimeException.class)
-    public void testGetSchemas() throws Exception {
-        doThrow(RuntimeException.class).when(operationProvider).openSnapshot(anyString());
-        service.getSchemas();
-    }
-
-    @Test(expected = IllegalStateException.class)
-    public void testGetSchemas2() throws Exception {
-        doThrow(Exception.class).when(operationProvider).openSnapshot(anyString());
-        service.getSchemas();
-    }
-
-    @Test
-    public void testGetSchemas3() throws Exception {
-        doReturn("").when(managementSession).toString();
-        Capability cap = mock(Capability.class);
-        Set<Capability> caps = Sets.newHashSet(cap);
-        Set<NetconfOperationService> services = Sets.newHashSet(operationService);
-        doReturn(snapshot).when(operationProvider).openSnapshot(anyString());
-        doReturn(services).when(snapshot).getServices();
-        doReturn(caps).when(operationService).getCapabilities();
-        Optional<String> opt = mock(Optional.class);
-        doReturn(opt).when(cap).getCapabilitySchema();
-        doReturn(true).when(opt).isPresent();
-        doReturn(opt).when(cap).getModuleNamespace();
-        doReturn("namespace").when(opt).get();
-        Optional<String> optRev = Optional.of("rev");
-        doReturn(optRev).when(cap).getRevision();
-        doReturn(Optional.of("modName")).when(cap).getModuleName();
-        doReturn(Lists.newArrayList("loc")).when(cap).getLocation();
-        doNothing().when(snapshot).close();
-
-        assertNotNull(service.getSchemas());
-        verify(snapshot, times(1)).close();
-
-        NetconfServerSessionListener sessionListener = mock(NetconfServerSessionListener.class);
-        Channel channel = mock(Channel.class);
-        doReturn("mockChannel").when(channel).toString();
-        NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader("name", "addr", "2", "tcp", "id");
-        NetconfServerSession sm = new NetconfServerSession(sessionListener, channel, 10, header);
-        doNothing().when(sessionListener).onSessionUp(any(NetconfServerSession.class));
-        sm.sessionUp();
-        service.onSessionUp(sm);
-        assertEquals(1, service.getSessions().getSession().size());
-
-        assertEquals(Long.valueOf(10), service.getSessions().getSession().get(0).getSessionId());
-
-        service.onSessionDown(sm);
-        assertEquals(0, service.getSessions().getSession().size());
-    }
+    // TODO redo test
 }
index 15aeb8d27c8badbafa64db0a7614174ce7155ceb..aa8c0a0f60f0a6ccb8ede18eef89a47549ee8f36 100644 (file)
@@ -22,9 +22,9 @@ import com.google.common.collect.Sets;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerSession;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
@@ -38,7 +38,7 @@ public class DefaultCommitTest {
     private Document requestMessage;
     private NetconfOperationRouter router;
     private DefaultCommitNotificationProducer notifier;
-    private CapabilityProvider cap;
+    private NetconfMonitoringService cap;
     private DefaultCommit commit;
 
     @Before
@@ -49,7 +49,7 @@ public class DefaultCommitTest {
         doReturn(false).when(operation).isExecutionTermination();
         notifier = mock(DefaultCommitNotificationProducer.class);
         doNothing().when(notifier).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
-        cap = mock(CapabilityProvider.class);
+        cap = mock(NetconfMonitoringService.class);
         doReturn(Sets.newHashSet()).when(cap).getCapabilities();
         Document rpcData = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
         doReturn(rpcData).when(router).onNetconfMessage(any(Document.class), any(NetconfServerSession.class));
index 413c9cc9452334640e3aab9269def616e99b1ff3..2fb989507c54f7f3aa065407a6664d554c7cd051 100644 (file)
@@ -12,7 +12,6 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.anyString;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
 import java.util.Arrays;
@@ -44,11 +43,11 @@ public class NetconfImplActivatorTest {
         doReturn(filter).when(bundle).createFilter(anyString());
         doNothing().when(bundle).addServiceListener(any(ServiceListener.class), anyString());
 
-        ServiceReference<?>[] refs = new ServiceReference[0];
+        ServiceReference<?>[] refs = {};
         doReturn(refs).when(bundle).getServiceReferences(anyString(), anyString());
         doReturn(Arrays.asList(refs)).when(bundle).getServiceReferences(any(Class.class), anyString());
         doReturn("").when(bundle).getProperty(anyString());
-        doReturn(registration).when(bundle).registerService(any(Class.class), any(NetconfOperationServiceFactoryListenerImpl.class), any(Dictionary.class));
+        doReturn(registration).when(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
         doNothing().when(registration).unregister();
         doNothing().when(bundle).removeServiceListener(any(ServiceListener.class));
     }
@@ -57,7 +56,7 @@ public class NetconfImplActivatorTest {
     public void testStart() throws Exception {
         NetconfImplActivator activator = new NetconfImplActivator();
         activator.start(bundle);
-        verify(bundle, times(2)).registerService(any(Class.class), any(NetconfOperationServiceFactoryListenerImpl.class), any(Dictionary.class));
+        verify(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
         activator.stop(bundle);
     }
 }
index b70e97bac9289f15a3793473fb43cc026b6ce121..c2812dbf61af7241323941a9317780dd4e7df100 100644 (file)
@@ -13,7 +13,6 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anySetOf;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
 import io.netty.channel.Channel;
@@ -47,6 +46,7 @@ import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesMod
 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
@@ -57,13 +57,11 @@ import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProduce
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
+import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
 import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
@@ -108,14 +106,16 @@ public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
 
         setUpTestInitial();
 
-        final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
+        final AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
+        final NetconfMonitoringService netconfMonitoringService = getNetconfMonitoringService(factoriesListener);
         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
+        factoriesListener.onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(new NetconfMonitoringOperationService(netconfMonitoringService)));
 
-        for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories()) {
+        for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories(factoriesListener)) {
             factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
         }
 
-        serverTcpChannel = startNetconfTcpServer(factoriesListener);
+        serverTcpChannel = startNetconfTcpServer(factoriesListener, netconfMonitoringService);
         clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
     }
 
@@ -137,8 +137,8 @@ public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
         return get;
     }
 
-    private Channel startNetconfTcpServer(final NetconfOperationServiceFactoryListenerImpl factoriesListener) throws Exception {
-        final NetconfServerDispatcherImpl dispatch = createDispatcher(factoriesListener, getNetconfMonitoringService(), getNotificationProducer());
+    private Channel startNetconfTcpServer(final AggregatedNetconfOperationServiceFactory listener, final NetconfMonitoringService monitoring) throws Exception {
+        final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring, getNotificationProducer());
 
         final ChannelFuture s;
         if(getTcpServerAddress() instanceof LocalAddress) {
@@ -157,16 +157,12 @@ public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
         return notificationProducer;
     }
 
-    protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories() {
+    protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories(final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
         return Collections.emptySet();
     }
 
-    protected SessionMonitoringService getNetconfMonitoringService() throws Exception {
-        final NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
-        final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
-        doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
-        doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
-        return new NetconfMonitoringServiceImpl(netconfOperationProvider);
+    protected NetconfMonitoringService getNetconfMonitoringService(final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
+        return new NetconfMonitoringServiceImpl(factoriesListener);
     }
 
     protected abstract SocketAddress getTcpServerAddress();
@@ -206,7 +202,7 @@ public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
     }
 
     protected NetconfServerDispatcherImpl createDispatcher(
-            final NetconfOperationServiceFactoryListenerImpl factoriesListener, final SessionMonitoringService sessionMonitoringService,
+            final AggregatedNetconfOperationServiceFactory factoriesListener, final NetconfMonitoringService sessionMonitoringService,
             final DefaultCommitNotificationProducer commitNotifier) {
         final SessionIdProvider idProvider = new SessionIdProvider();
 
index 92c96d92f28962eeb88ccc961665d852cd39364c..379c23af3ca1797eea4a4a01addfa142cff76d4d 100644 (file)
@@ -9,23 +9,18 @@ package org.opendaylight.controller.netconf.it;
 
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithName;
 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertElementsCount;
 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToDocument;
 
 import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
 import java.io.IOException;
 import java.lang.management.ManagementFactory;
 import java.net.InetSocketAddress;
 import java.net.SocketAddress;
-import java.util.Collections;
 import java.util.List;
-import java.util.Set;
 import javax.management.InstanceNotFoundException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
@@ -38,15 +33,6 @@ import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
-import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
 import org.w3c.dom.Document;
@@ -58,29 +44,12 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
     public static final int PORT = 12026;
     private static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
 
-    private NetconfMonitoringServiceImpl netconfMonitoringService;
-
-    @Override
-    protected void setUpTestInitial() {
-        netconfMonitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider());
-    }
-
-    @Override
-    protected SessionMonitoringService getNetconfMonitoringService() throws Exception {
-        return netconfMonitoringService;
-    }
 
     @Override
     protected SocketAddress getTcpServerAddress() {
         return TCP_ADDRESS;
     }
 
-    @Override
-    protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories() {
-        return Collections.<NetconfOperationServiceFactory>singletonList(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
-                new NetconfMonitoringOperationService(netconfMonitoringService)));
-    }
-
     @Override
     protected DefaultCommitNotificationProducer getNotificationProducer() {
         return new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
@@ -95,7 +64,6 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
             try (ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler(
                     platformMBeanServer, mockedAggregator)) {
 
-
                 try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) {
                     NetconfMessage response = netconfClient.sendMessage(loadGetConfigMessage());
                     assertContainsElementWithName(response.getDocument(), "modules");
@@ -143,20 +111,6 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
         return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml");
     }
 
-
-    public NetconfOperationProvider getNetconfOperationProvider() {
-        final NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class);
-        final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
-        final NetconfOperationService service = mock(NetconfOperationService.class);
-        final Set<Capability> caps = Sets.newHashSet();
-        doReturn(caps).when(service).getCapabilities();
-        final Set<NetconfOperationService> services = Sets.newHashSet(service);
-        doReturn(services).when(snap).getServices();
-        doReturn(snap).when(factoriesListener).openSnapshot(anyString());
-
-        return factoriesListener;
-    }
-
     private static class VerifyingNotificationListener implements NotificationListener {
         public List<Notification> notifications = Lists.newArrayList();
 
index ea94fd3f8bbf9d5c56f697877b88905e89740335..e745b393fbcb271868e0f9e2c68366a6b44f38c1 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.netconf.it;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
@@ -26,21 +27,14 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 import org.junit.Test;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
-import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
 import org.w3c.dom.Document;
 
 public class NetconfITMonitoringTest extends AbstractNetconfConfigTest {
@@ -49,45 +43,11 @@ public class NetconfITMonitoringTest extends AbstractNetconfConfigTest {
     public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
     public static final TestingCapability TESTING_CAPABILITY = new TestingCapability();
 
-    private NetconfMonitoringServiceImpl netconfMonitoringService;
-
-    @Override
-    protected void setUpTestInitial() {
-        netconfMonitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider());
-    }
-
-    @Override
-    protected SessionMonitoringService getNetconfMonitoringService() throws Exception {
-        return netconfMonitoringService;
-    }
-
-    @Override
-    protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories() {
-        return Collections.<NetconfOperationServiceFactory>singletonList(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
-                new NetconfMonitoringOperationService(netconfMonitoringService)));
-    }
-
     @Override
     protected InetSocketAddress getTcpServerAddress() {
         return TCP_ADDRESS;
     }
 
-    static SessionMonitoringService getNetconfMonitoringListenerService(final Logger LOG, final NetconfMonitoringServiceImpl monitor) {
-        return new SessionMonitoringService() {
-            @Override
-            public void onSessionUp(final NetconfManagementSession session) {
-                LOG.debug("Management session up {}", session);
-                monitor.onSessionUp(session);
-            }
-
-            @Override
-            public void onSessionDown(final NetconfManagementSession session) {
-                LOG.debug("Management session down {}", session);
-                monitor.onSessionDown(session);
-            }
-        };
-    }
-
     @Test
     public void testGetResponseFromMonitoring() throws Exception {
         try (TestingNetconfClient netconfClient = new TestingNetconfClient("client-monitoring", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 10000))) {
@@ -151,23 +111,24 @@ public class NetconfITMonitoringTest extends AbstractNetconfConfigTest {
         assertEquals("Incorrect number of session-id tags in " + XmlUtil.toString(document), i, elementSize);
     }
 
-    public static NetconfOperationProvider getNetconfOperationProvider() {
-        final NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class);
-        final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
+    public static AggregatedNetconfOperationServiceFactory getNetconfOperationProvider() throws Exception {
+        final AggregatedNetconfOperationServiceFactory factoriesListener = mock(AggregatedNetconfOperationServiceFactory.class);
+        final NetconfOperationService snap = mock(NetconfOperationService.class);
         try {
             doNothing().when(snap).close();
         } catch (final Exception e) {
             // not happening
             throw new IllegalStateException(e);
         }
-        final NetconfOperationService service = mock(NetconfOperationService.class);
         final Set<Capability> caps = Sets.newHashSet();
         caps.add(TESTING_CAPABILITY);
 
-        doReturn(caps).when(service).getCapabilities();
-        final Set<NetconfOperationService> services = Sets.newHashSet(service);
-        doReturn(services).when(snap).getServices();
-        doReturn(snap).when(factoriesListener).openSnapshot(anyString());
+        doReturn(caps).when(factoriesListener).getCapabilities();
+        doReturn(snap).when(factoriesListener).createService(anyString());
+
+        AutoCloseable mock = mock(AutoCloseable.class);
+        doNothing().when(mock).close();
+        doReturn(mock).when(factoriesListener).registerCapabilityListener(any(CapabilityListener.class));
 
         return factoriesListener;
     }
diff --git a/opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationProvider.java b/opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationProvider.java
deleted file mode 100644 (file)
index f5c50f8..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.mapping.api;
-
-public interface NetconfOperationProvider {
-
-    NetconfOperationServiceSnapshot openSnapshot(String sessionIdForReporting);
-
-    public static class NetconfOperationProviderUtil {
-
-        public static String getNetconfSessionIdForReporting(long sessionId) {
-            return "netconf session id " + sessionId;
-        }
-
-    }
-
-}
index 5e2cba2cbaeea86985a9bf33fedbb2c30ee78ebf..1a1a124895f240f1a85cfefd78c4172c04391b65 100644 (file)
@@ -15,11 +15,6 @@ import java.util.Set;
  */
 public interface NetconfOperationService extends AutoCloseable {
 
-    /**
-     * Get capabilities announced by server hello message.
-     */
-    Set<Capability> getCapabilities();
-
     /**
      * Get set of netconf operations that are handled by this service.
      */
index 81401f26eecc4796a61f2740b079a7351e33007a..8caa177bfa525dd87ce38a1e914d1920dc1dc1be 100644 (file)
@@ -8,6 +8,10 @@
 
 package org.opendaylight.controller.netconf.mapping.api;
 
+import java.util.Set;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
+
 /**
  * Factory that must be registered in OSGi service registry in order to be used
  * by netconf-impl. Responsible for creating per-session instances of
@@ -15,6 +19,16 @@ package org.opendaylight.controller.netconf.mapping.api;
  */
 public interface NetconfOperationServiceFactory {
 
+    /**
+     * Get capabilities supported by current operation service.
+     */
+    Set<Capability> getCapabilities();
+
+    /**
+     * Supported capabilities may change over time, registering a listener allows for push based information retrieval about current notifications
+     */
+    AutoCloseable registerCapabilityListener(CapabilityListener listener);
+
     NetconfOperationService createService(String netconfSessionIdForReporting);
 
 }
diff --git a/opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationServiceSnapshot.java b/opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/NetconfOperationServiceSnapshot.java
deleted file mode 100644 (file)
index eaa6937..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.mapping.api;
-
-import java.util.Set;
-
-public interface NetconfOperationServiceSnapshot extends AutoCloseable {
-    String getNetconfSessionIdForReporting();
-
-    Set<NetconfOperationService> getServices();
-
-}
@@ -1,19 +1,19 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2015 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.netconf.impl.mapping.operations;
+package org.opendaylight.controller.netconf.monitoring;
 
 import com.google.common.base.Optional;
 import com.google.common.collect.Maps;
 import java.util.Map;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
 import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
@@ -23,16 +23,16 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-public final class DefaultGetSchema extends AbstractLastNetconfOperation {
+public class GetSchema extends AbstractLastNetconfOperation {
     public static final String GET_SCHEMA = "get-schema";
     public static final String IDENTIFIER = "identifier";
     public static final String VERSION = "version";
 
-    private static final Logger LOG = LoggerFactory.getLogger(DefaultGetSchema.class);
-    private final CapabilityProvider cap;
+    private static final Logger LOG = LoggerFactory.getLogger(GetSchema.class);
+    private final NetconfMonitoringService cap;
 
-    public DefaultGetSchema(CapabilityProvider cap, String netconfSessionIdForReporting) {
-        super(netconfSessionIdForReporting);
+    public GetSchema(final NetconfMonitoringService cap) {
+        super(MonitoringConstants.MODULE_NAME);
         this.cap = cap;
     }
 
@@ -47,16 +47,16 @@ public final class DefaultGetSchema extends AbstractLastNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
-        GetSchemaEntry entry;
+    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws NetconfDocumentedException {
+        final GetSchemaEntry entry;
 
         entry = new GetSchemaEntry(xml);
 
-        String schema;
+        final String schema;
         try {
             schema = cap.getSchemaForCapability(entry.identifier, entry.version);
-        } catch (IllegalStateException e) {
-            Map<String, String> errorInfo = Maps.newHashMap();
+        } catch (final IllegalStateException e) {
+            final Map<String, String> errorInfo = Maps.newHashMap();
             errorInfo.put(entry.identifier, e.getMessage());
             LOG.warn("Rpc error: {}", NetconfDocumentedException.ErrorTag.operation_failed, e);
             throw new NetconfDocumentedException(e.getMessage(), NetconfDocumentedException.ErrorType.application,
@@ -64,7 +64,7 @@ public final class DefaultGetSchema extends AbstractLastNetconfOperation {
                     NetconfDocumentedException.ErrorSeverity.error, errorInfo);
         }
 
-        Element getSchemaResult;
+        final Element getSchemaResult;
         getSchemaResult = XmlUtil.createTextElement(document, XmlNetconfConstants.DATA_KEY, schema,
                 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING));
         LOG.trace("{} operation successful", GET_SCHEMA);
@@ -76,19 +76,19 @@ public final class DefaultGetSchema extends AbstractLastNetconfOperation {
         private final String identifier;
         private final Optional<String> version;
 
-        GetSchemaEntry(XmlElement getSchemaElement) throws NetconfDocumentedException {
+        GetSchemaEntry(final XmlElement getSchemaElement) throws NetconfDocumentedException {
             getSchemaElement.checkName(GET_SCHEMA);
             getSchemaElement.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING);
 
             XmlElement identifierElement = null;
             try {
                 identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
-            } catch (MissingNameSpaceException e) {
+            } catch (final MissingNameSpaceException e) {
                 LOG.trace("Can't get identifier element as only child element with same namespace due to ",e);
                 throw NetconfDocumentedException.wrap(e);
             }
             identifier = identifierElement.getTextContent();
-            Optional<XmlElement> versionElement = getSchemaElement
+            final Optional<XmlElement> versionElement = getSchemaElement
                     .getOnlyChildElementWithSameNamespaceOptionally(VERSION);
             if (versionElement.isPresent()) {
                 version = Optional.of(versionElement.get().getTextContent());
index 1411350cd3dce0fec1d4854e3eeabe580c4aef4d..1b0a50b8304dbcd335eea01df0038737f46958af 100644 (file)
@@ -7,8 +7,18 @@
 */
 package org.opendaylight.controller.netconf.monitoring.osgi;
 
+import com.google.common.base.Optional;
+import com.google.common.collect.Sets;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
@@ -31,22 +41,84 @@ public class NetconfMonitoringActivator implements BundleActivator {
         if(monitor!=null) {
             try {
                 monitor.close();
-            } catch (Exception e) {
+            } catch (final Exception e) {
                 LOG.warn("Ignoring exception while closing {}", monitor, e);
             }
         }
     }
 
-    public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory {
+    public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory, AutoCloseable {
+
         private final NetconfMonitoringOperationService operationService;
 
-        public NetconfMonitoringOperationServiceFactory(NetconfMonitoringOperationService operationService) {
+        private static final Set<Capability> CAPABILITIES = Sets.<Capability>newHashSet(new Capability() {
+
+            @Override
+            public String getCapabilityUri() {
+                return MonitoringConstants.URI;
+            }
+
+            @Override
+            public Optional<String> getModuleNamespace() {
+                return Optional.of(MonitoringConstants.NAMESPACE);
+            }
+
+            @Override
+            public Optional<String> getModuleName() {
+                return Optional.of(MonitoringConstants.MODULE_NAME);
+            }
+
+            @Override
+            public Optional<String> getRevision() {
+                return Optional.of(MonitoringConstants.MODULE_REVISION);
+            }
+
+            @Override
+            public Optional<String> getCapabilitySchema() {
+                return Optional.absent();
+            }
+
+            @Override
+            public Collection<String> getLocation() {
+                return Collections.emptyList();
+            }
+        });
+
+        private static final AutoCloseable AUTO_CLOSEABLE = new AutoCloseable() {
+            @Override
+            public void close() throws Exception {
+                // NOOP
+            }
+        };
+
+        private final List<CapabilityListener> listeners = new ArrayList<>();
+
+        public NetconfMonitoringOperationServiceFactory(final NetconfMonitoringOperationService operationService) {
             this.operationService = operationService;
         }
 
         @Override
-        public NetconfOperationService createService(String netconfSessionIdForReporting) {
+        public NetconfOperationService createService(final String netconfSessionIdForReporting) {
             return operationService;
         }
+
+        @Override
+        public Set<Capability> getCapabilities() {
+            return CAPABILITIES;
+        }
+
+        @Override
+        public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+            listener.onCapabilitiesAdded(getCapabilities());
+            listeners.add(listener);
+            return AUTO_CLOSEABLE;
+        }
+
+        @Override
+        public void close() {
+            for (final CapabilityListener listener : listeners) {
+                listener.onCapabilitiesRemoved(getCapabilities());
+            }
+        }
     }
 }
index a17e139131461bcc2c7ac12505f9d59ae207eba0..efe71e912739d9b5988b18bc6ecdf73a498f9424 100644 (file)
@@ -7,67 +7,25 @@
 */
 package org.opendaylight.controller.netconf.monitoring.osgi;
 
-import com.google.common.base.Optional;
 import com.google.common.collect.Sets;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.Set;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.monitoring.Get;
-import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
+import org.opendaylight.controller.netconf.monitoring.GetSchema;
 
 public class NetconfMonitoringOperationService implements NetconfOperationService {
 
-    private static final Set<Capability> CAPABILITIES = Sets.<Capability>newHashSet(new Capability() {
-
-        @Override
-        public String getCapabilityUri() {
-            return MonitoringConstants.URI;
-        }
-
-        @Override
-        public Optional<String> getModuleNamespace() {
-            return Optional.of(MonitoringConstants.NAMESPACE);
-        }
-
-        @Override
-        public Optional<String> getModuleName() {
-            return Optional.of(MonitoringConstants.MODULE_NAME);
-        }
-
-        @Override
-        public Optional<String> getRevision() {
-            return Optional.of(MonitoringConstants.MODULE_REVISION);
-        }
-
-        @Override
-        public Optional<String> getCapabilitySchema() {
-            return Optional.absent();
-        }
-
-        @Override
-        public Collection<String> getLocation() {
-            return Collections.emptyList();
-        }
-    });
-
     private final NetconfMonitoringService monitor;
 
     public NetconfMonitoringOperationService(final NetconfMonitoringService monitor) {
         this.monitor = monitor;
     }
 
-    @Override
-    public Set<Capability> getCapabilities() {
-        return CAPABILITIES;
-    }
-
     @Override
     public Set<NetconfOperation> getNetconfOperations() {
-        return Sets.<NetconfOperation>newHashSet(new Get(monitor));
+        return Sets.<NetconfOperation>newHashSet(new Get(monitor), new GetSchema(monitor));
     }
 
     @Override
index 9e7c105aa4e0cf53f95ebeb290b181866e54cc8a..5d0a2a91ad59f95ea20df53b7bc62433479f4650 100644 (file)
@@ -25,6 +25,7 @@ public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonit
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceTracker.class);
 
     private ServiceRegistration<NetconfOperationServiceFactory> reg;
+    private NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory factory;
 
     NetconfMonitoringServiceTracker(final BundleContext context) {
         super(context, NetconfMonitoringService.class, null);
@@ -38,7 +39,7 @@ public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonit
 
         final NetconfMonitoringOperationService operationService = new NetconfMonitoringOperationService(
                 netconfMonitoringService);
-        final NetconfOperationServiceFactory factory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
+        factory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
                 operationService);
 
         Dictionary<String, String> properties = new Hashtable<>();
@@ -58,6 +59,9 @@ public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonit
                 LOG.warn("Ignoring exception while unregistering {}", reg, e);
             }
         }
+        if(factory!=null) {
+            factory.close();
+        }
     }
 
 }
@@ -1,12 +1,12 @@
 /*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2015 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.netconf.impl.mapping.operations;
+package org.opendaylight.controller.netconf.monitoring;
 
 import static org.junit.Assert.assertNotNull;
 import static org.mockito.Matchers.any;
@@ -19,20 +19,21 @@ import com.google.common.base.Optional;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.w3c.dom.Document;
 
-public class DefaultGetSchemaTest {
+public class GetSchemaTest {
 
-    private CapabilityProvider cap;
+
+    private NetconfMonitoringService cap;
     private Document doc;
     private String getSchema;
 
     @Before
     public void setUp() throws Exception {
-        cap = mock(CapabilityProvider.class);
+        cap = mock(NetconfMonitoringService.class);
         doc = XmlUtil.newDocument();
         getSchema = "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
                 "        <identifier>threadpool-api</identifier>\n" +
@@ -45,15 +46,16 @@ public class DefaultGetSchemaTest {
 
     @Test(expected = NetconfDocumentedException.class)
     public void testDefaultGetSchema() throws Exception {
-        DefaultGetSchema schema = new DefaultGetSchema(cap, "");
+        GetSchema schema = new GetSchema(cap);
         doThrow(IllegalStateException.class).when(cap).getSchemaForCapability(anyString(), any(Optional.class));
         schema.handleWithNoSubsequentOperations(doc, XmlElement.fromDomElement(XmlUtil.readXmlToElement(getSchema)));
     }
 
     @Test
     public void handleWithNoSubsequentOperations() throws Exception {
-        DefaultGetSchema schema = new DefaultGetSchema(cap, "");
+        GetSchema schema = new GetSchema(cap);
         doReturn("").when(cap).getSchemaForCapability(anyString(), any(Optional.class));
         assertNotNull(schema.handleWithNoSubsequentOperations(doc, XmlElement.fromDomElement(XmlUtil.readXmlToElement(getSchema))));
     }
-}
+
+}
\ No newline at end of file
index 7873183188bb36c56ae93d8fce996bc18b504d6f..3a0362277ed9d97b8609e4a2bda6ecc6c78acbe8 100644 (file)
@@ -22,14 +22,15 @@ public class NetconfMonitoringOperationServiceTest {
     public void testGetters() throws Exception {
         NetconfMonitoringService monitor = mock(NetconfMonitoringService.class);
         NetconfMonitoringOperationService service = new NetconfMonitoringOperationService(monitor);
+        NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory serviceFactory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(service);
 
-        assertEquals(1, service.getNetconfOperations().size());
+        assertEquals(2, service.getNetconfOperations().size());
 
-        assertEquals(Optional.<String>absent(), service.getCapabilities().iterator().next().getCapabilitySchema());
-        assertEquals(Collections.<String>emptyList(), service.getCapabilities().iterator().next().getLocation());
-        assertEquals(Optional.of(MonitoringConstants.MODULE_REVISION), service.getCapabilities().iterator().next().getRevision());
-        assertEquals(Optional.of(MonitoringConstants.MODULE_NAME), service.getCapabilities().iterator().next().getModuleName());
-        assertEquals(Optional.of(MonitoringConstants.NAMESPACE), service.getCapabilities().iterator().next().getModuleNamespace());
-        assertEquals(MonitoringConstants.URI, service.getCapabilities().iterator().next().getCapabilityUri());
+        assertEquals(Optional.<String>absent(), serviceFactory.getCapabilities().iterator().next().getCapabilitySchema());
+        assertEquals(Collections.<String>emptyList(), serviceFactory.getCapabilities().iterator().next().getLocation());
+        assertEquals(Optional.of(MonitoringConstants.MODULE_REVISION), serviceFactory.getCapabilities().iterator().next().getRevision());
+        assertEquals(Optional.of(MonitoringConstants.MODULE_NAME), serviceFactory.getCapabilities().iterator().next().getModuleName());
+        assertEquals(Optional.of(MonitoringConstants.NAMESPACE), serviceFactory.getCapabilities().iterator().next().getModuleNamespace());
+        assertEquals(MonitoringConstants.URI, serviceFactory.getCapabilities().iterator().next().getCapabilityUri());
     }
 }
index 4b5dcd7d5578941523d0b76eb6f88aa97c353b13..b81d2c144fd38f088db974dba8cd19952ac0dde7 100644 (file)
@@ -11,9 +11,13 @@ import static org.hamcrest.MatcherAssert.assertThat;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
+import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
+import java.util.Set;
 import org.hamcrest.CoreMatchers;
 import org.junit.Test;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
@@ -42,6 +46,26 @@ public class JaxBSerializerTest {
 
         final NetconfMonitoringService service = new NetconfMonitoringService() {
 
+            @Override
+            public void onSessionUp(final NetconfManagementSession session) {
+
+            }
+
+            @Override
+            public void onSessionDown(final NetconfManagementSession session) {
+
+            }
+
+            @Override
+            public void onCapabilitiesAdded(final Set<Capability> addedCaps) {
+
+            }
+
+            @Override
+            public void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
+
+            }
+
             @Override
             public Sessions getSessions() {
                 return new SessionsBuilder().setSession(Lists.newArrayList(getMockSession(NetconfTcp.class), getMockSession(NetconfSsh.class))).build();
@@ -51,6 +75,16 @@ public class JaxBSerializerTest {
             public Schemas getSchemas() {
                 return new SchemasBuilder().setSchema(Lists.newArrayList(getMockSchema("id", "v1", Yang.class), getMockSchema("id2", "", Yang.class))).build();
             }
+
+            @Override
+            public String getSchemaForCapability(final String moduleName, final Optional<String> revision) {
+                return null;
+            }
+
+            @Override
+            public Set<String> getCapabilities() {
+                return null;
+            }
         };
         final NetconfState model = new NetconfState(service);
         final String xml = XmlUtil.toString(new JaxBSerializer().toXml(model)).replaceAll("\\s", "");
index 9eab5caff74fe3411d0ccaa847594d1834e574ea..a0a0dfcb8f5e506071daa1b5b894aa0074f556ca 100644 (file)
@@ -15,8 +15,9 @@ import java.util.Collections;
 import java.util.Dictionary;
 import java.util.Hashtable;
 import java.util.Set;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
 import org.opendaylight.controller.netconf.api.util.NetconfConstants;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
@@ -42,16 +43,30 @@ public class Activator implements BundleActivator {
 
         final NetconfOperationServiceFactory netconfOperationServiceFactory = new NetconfOperationServiceFactory() {
 
+            private final Set<Capability> capabilities = Collections.<Capability>singleton(new NotificationsCapability());
+
+            @Override
+            public Set<Capability> getCapabilities() {
+                return capabilities;
+            }
+
+            @Override
+            public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+                listener.onCapabilitiesAdded(capabilities);
+                return new AutoCloseable() {
+                    @Override
+                    public void close() {
+                        listener.onCapabilitiesRemoved(capabilities);
+                    }
+                };
+            }
+
             @Override
             public NetconfOperationService createService(final String netconfSessionIdForReporting) {
                 return new NetconfOperationService() {
 
                     private final CreateSubscription createSubscription = new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
 
-                    @Override
-                    public Set<Capability> getCapabilities() {
-                        return Collections.<Capability>singleton(new NotificationsCapability());
-                    }
 
                     @Override
                     public Set<NetconfOperation> getNetconfOperations() {
@@ -68,7 +83,7 @@ public class Activator implements BundleActivator {
             }
         };
 
-        Dictionary<String, String> properties = new Hashtable<>();
+        final Dictionary<String, String> properties = new Hashtable<>();
         properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_MONITORING);
         operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
 
index fcb513f0165265fbf09d5ab68df8693e07c3753f..3aba6f81a3bc04770c21d5725efe90b582113594 100644 (file)
@@ -12,8 +12,8 @@ import com.google.common.base.Optional;
 import java.util.Collections;
 import java.util.Date;
 import java.util.List;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
 
index 68f8796d819f301b20f0d17e274fc0b981cb9816..11af568321cf59cba2cf62077787f19fb8e266e9 100644 (file)
@@ -12,8 +12,8 @@ import com.google.common.base.Optional;
 import java.util.Collections;
 import java.util.Date;
 import java.util.List;
+import org.opendaylight.controller.netconf.api.Capability;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
 
index 30b307658964c59706818fff40846a135387cb28..bb67af2032793fdac1a8038377c8550b5f045d50 100644 (file)
@@ -55,19 +55,20 @@ import org.apache.sshd.common.util.ThreadUtils;
 import org.apache.sshd.server.PasswordAuthenticator;
 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
 import org.apache.sshd.server.session.ServerSession;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
+import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
+import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
+import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
-import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
+import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
@@ -141,9 +142,15 @@ public class NetconfDeviceSimulator implements Closeable {
 
         final SessionIdProvider idProvider = new SessionIdProvider();
 
+
+        final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
         final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
-        final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
-        simulatedOperationProvider.addService(monitoringService);
+
+        final NetconfMonitoringService monitoringService1 = new NetconfMonitoringServiceImpl(aggregatedNetconfOperationServiceFactory);
+        final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
+                new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(new NetconfMonitoringOperationService(monitoringService1));
+        aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(simulatedOperationProvider);
+        aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
 
         final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
@@ -152,7 +159,7 @@ public class NetconfDeviceSimulator implements Closeable {
                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
 
         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
+                hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, commitNotifier, monitoringService1, serverCapabilities);
 
         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
                 serverNegotiatorFactory);
@@ -396,65 +403,43 @@ public class NetconfDeviceSimulator implements Closeable {
         // close Everything
     }
 
-    private static class SimulatedOperationProvider implements NetconfOperationProvider {
-        private final SessionIdProvider idProvider;
-        private final Set<NetconfOperationService> netconfOperationServices;
+    private static class SimulatedOperationProvider implements NetconfOperationServiceFactory {
+        private final Set<Capability> caps;
+        private final SimulatedOperationService simulatedOperationService;
 
 
         public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps, final Optional<File> notificationsFile) {
-            this.idProvider = idProvider;
-            final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId(), notificationsFile);
-            this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
+            this.caps = caps;
+            simulatedOperationService = new SimulatedOperationService(idProvider.getCurrentSessionId(), notificationsFile);
         }
 
         @Override
-        public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
-            return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
+        public Set<Capability> getCapabilities() {
+            return caps;
         }
 
-        public void addService(final NetconfOperationService monitoringService) {
-            netconfOperationServices.add(monitoringService);
+        @Override
+        public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
+            return new AutoCloseable() {
+                @Override
+                public void close() throws Exception {}
+            };
         }
 
-        private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
-            private final SessionIdProvider idProvider;
-            private final Set<NetconfOperationService> netconfOperationServices;
-
-            public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
-                this.idProvider = idProvider;
-                this.netconfOperationServices = netconfOperationServices;
-            }
-
-            @Override
-            public String getNetconfSessionIdForReporting() {
-                return String.valueOf(idProvider.getCurrentSessionId());
-            }
-
-            @Override
-            public Set<NetconfOperationService> getServices() {
-                return netconfOperationServices;
-            }
-
-            @Override
-            public void close() throws Exception {}
+        @Override
+        public NetconfOperationService createService(final String netconfSessionIdForReporting) {
+            return simulatedOperationService;
         }
 
         static class SimulatedOperationService implements NetconfOperationService {
-            private final Set<Capability> capabilities;
             private final long currentSessionId;
             private final Optional<File> notificationsFile;
 
-            public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId, final Optional<File> notificationsFile) {
-                this.capabilities = capabilities;
+            public SimulatedOperationService(final long currentSessionId, final Optional<File> notificationsFile) {
                 this.currentSessionId = currentSessionId;
                 this.notificationsFile = notificationsFile;
             }
 
-            @Override
-            public Set<Capability> getCapabilities() {
-                return capabilities;
-            }
-
             @Override
             public Set<NetconfOperation> getNetconfOperations() {
                 final DataList storage = new DataList();
@@ -475,16 +460,4 @@ public class NetconfDeviceSimulator implements Closeable {
         }
     }
 
-    private class LoggingMonitoringService implements SessionMonitoringService {
-        @Override
-        public void onSessionUp(final NetconfManagementSession session) {
-            LOG.debug("Session {} established", session);
-        }
-
-        @Override
-        public void onSessionDown(final NetconfManagementSession session) {
-            LOG.debug("Session {} down", session);
-        }
-    }
-
 }