Merge "Yang Changes to include list<actions> to PacketOut - Added list<actions> and...
authorEd Warnicke <eaw@cisco.com>
Mon, 3 Feb 2014 16:34:53 +0000 (16:34 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 3 Feb 2014 16:34:53 +0000 (16:34 +0000)
68 files changed:
opendaylight/archetypes/odl-model-project/src/main/resources/archetype-resources/pom.xml
opendaylight/commons/opendaylight/pom.xml
opendaylight/config/config-persister-directory-autodetect-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/autodetect/AutodetectDirectoryPersisterTest.java
opendaylight/config/config-persister-directory-autodetect-adapter/src/test/resources/bad_controller.xml.config [new file with mode: 0644]
opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/CapabilityHandler.java [deleted file]
opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java
opendaylight/distribution/opendaylight/pom.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini
opendaylight/md-sal/clustered-data-store/implementation/pom.xml
opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-meter-types.yang
opendaylight/md-sal/pom.xml
opendaylight/md-sal/sal-binding-broker/pom.xml
opendaylight/md-sal/sal-binding-config/pom.xml
opendaylight/md-sal/sal-common-api/pom.xml
opendaylight/md-sal/sal-common-util/pom.xml
opendaylight/md-sal/sal-dom-api/pom.xml
opendaylight/md-sal/sal-dom-broker/pom.xml
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.xtend
opendaylight/md-sal/sal-netconf-connector/pom.xml
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java
opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang
opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft01.java [deleted file]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfServiceLegacy.java [deleted file]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.xtend
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MediaTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPutOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/json/jsondata_leaf_list.json [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmldata_leaf_list.xml [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/yang/augment-module-leaf-list.yang [new file with mode: 0644]
opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClient.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcher.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiator.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorFactory.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfSshClientDispatcher.java
opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SSHNetconfClientLiveTest.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java
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/osgi/NetconfImplActivator.java
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-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java [new file with mode: 0644]
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/NetconfITSecureTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfMessageAggregator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java
opendaylight/web/root/src/main/resources/js/lib.js

index 70742bd550db0fccb8ed3203987650e224c6c5e0..ebb9302b78487282f2e40c802429161809ea6c4b 100644 (file)
@@ -9,8 +9,8 @@
   <properties>\r
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\r
     <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>\r
-    <yang.version>0.6.1</yang.version>\r
-    <yang.codegen.version>0.6.1</yang.codegen.version>\r
+    <yang.version>0.6.2-SNAPSHOT</yang.version>\r
+    <yang.codegen.version>0.6.2-SNAPSHOT</yang.codegen.version>\r
     <bundle.plugin.version>2.3.7</bundle.plugin.version>\r
   </properties>\r
   <scm>\r
index 47b31fb8056dcd2d73993ff94118e14de8e5aab7..9d4f8389925551c4142c4555b33e296d4cc11ec9 100644 (file)
@@ -69,7 +69,7 @@
     <enforcer.version>1.3.1</enforcer.version>
     <bundle.plugin.version>2.3.7</bundle.plugin.version>
     <junit.version>4.8.1</junit.version>
-    <yangtools.version>0.6.1</yangtools.version>
+    <yangtools.version>0.6.2-SNAPSHOT</yangtools.version>
     <!--versions for bits of the controller -->
     <controller.version>0.4.2-SNAPSHOT</controller.version>
     <hosttracker.api.version>0.5.2-SNAPSHOT</hosttracker.api.version>
index f8334607669103203f03f5c273dbaa7cf75a4977..bcade93352670fcae086cf75f776242d0886276e 100644 (file)
@@ -8,12 +8,15 @@
 package org.opendaylight.controller.config.persist.storage.directory.autodetect;
 
 import java.io.File;
+import java.io.IOException;
 import java.util.List;
 import junit.framework.Assert;
 import org.junit.Test;
 import org.junit.matchers.JUnitMatchers;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.test.PropertiesProviderTest;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
 
 public class AutodetectDirectoryPersisterTest {
 
@@ -37,5 +40,52 @@ public class AutodetectDirectoryPersisterTest {
         String snapFromXml = configs.get(1).getConfigSnapshot();
         org.junit.Assert.assertThat(snapFromXml, JUnitMatchers.containsString("<config>xml</config>"));
 
-        Assert.assertEquals(configs.get(0).getCapabilities(), configs.get(1).getCapabilities());    }
+        Assert.assertEquals(configs.get(0).getCapabilities(), configs.get(1).getCapabilities());
+    }
+
+    @Test
+    public void testInvalidXml() throws Exception {
+        File resourcePath = FileTypeTest.getResourceAsFile("/bad_controller.xml.config");
+        File parentFile = resourcePath.getParentFile();
+
+        AutodetectDirectoryStorageAdapter adapter = new AutodetectDirectoryStorageAdapter();
+
+        PropertiesProviderTest pp = new PropertiesProviderTest();
+        pp.addProperty("directoryStorage",parentFile.getPath());
+        AutodetectDirectoryPersister persister = (AutodetectDirectoryPersister) adapter.instantiate(pp);
+        try {
+            List<ConfigSnapshotHolder> configs = persister.loadLastConfigs();
+            fail("An exception of type " + IllegalStateException.class + " was expected");
+        } catch (IllegalStateException ise){
+            String message = ise.getMessage();
+            assertThat(message, JUnitMatchers.containsString("Unable to restore configuration snapshot from "));
+        }
+
+    }
+
+    @Test
+    public void testPersistConfig() throws Exception {
+        File resourcePath = FileTypeTest.getResourceAsFile("/combined/1controller.txt.config");
+        File parentFile = resourcePath.getParentFile();
+
+        AutodetectDirectoryStorageAdapter adapter = new AutodetectDirectoryStorageAdapter();
+
+        PropertiesProviderTest pp = new PropertiesProviderTest();
+        pp.addProperty("directoryStorage",parentFile.getPath());
+        AutodetectDirectoryPersister persister = (AutodetectDirectoryPersister) adapter.instantiate(pp);
+        List<ConfigSnapshotHolder> configs = null;
+        try {
+            configs = persister.loadLastConfigs();
+        } catch (IOException e) {
+            fail("An exception of type " + UnsupportedOperationException.class + " was expected");
+        }
+        Assert.assertEquals(2, configs.size());
+        try {
+            persister.persistConfig(configs.get(0));
+        } catch (UnsupportedOperationException uoe){
+            String message = uoe.getMessage();
+            assertThat(message,JUnitMatchers.containsString("This adapter is read only. Please set readonly=true on class"));
+        }
+    }
+
 }
diff --git a/opendaylight/config/config-persister-directory-autodetect-adapter/src/test/resources/bad_controller.xml.config b/opendaylight/config/config-persister-directory-autodetect-adapter/src/test/resources/bad_controller.xml.config
new file mode 100644 (file)
index 0000000..3f6a337
--- /dev/null
@@ -0,0 +1,10 @@
+<snapshot>
+    <required-capabilities>
+        <capability
+        <capability>cap2</capability>
+        <capability>capa a</capability>
+    </required-capabilities>
+    <configuration>
+        <config>xml</config>
+    </configuration>
+</snapshot>
\ No newline at end of file
diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/CapabilityHandler.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/CapabilityHandler.java
deleted file mode 100644 (file)
index d384df6..0000000
+++ /dev/null
@@ -1,47 +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.config.persist.storage.file.xml.model;
-
-import javax.xml.bind.ValidationEventHandler;
-import javax.xml.bind.annotation.DomHandler;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.StringWriter;
-
-class CapabilityHandler implements DomHandler<String, StreamResult> {
-
-    private static final String START_TAG = "<capability>";
-    private static final String END_TAG = "</capability>";
-
-    private StringWriter xmlWriter = new StringWriter();
-
-    public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
-        xmlWriter.getBuffer().setLength(0);
-        return new StreamResult(xmlWriter);
-    }
-
-    public String getElement(StreamResult rt) {
-        String xml = rt.getWriter().toString();
-        int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
-        int endIndex = xml.indexOf(END_TAG);
-        return xml.substring(beginIndex, endIndex);
-    }
-
-    public Source marshal(String n, ValidationEventHandler errorHandler) {
-        try {
-            String xml = START_TAG + n.trim() + END_TAG;
-            StringReader xmlReader = new StringReader(xml);
-            return new StreamSource(xmlReader);
-        } catch(Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-}
index 0e4cce544f049dc361ccc0770d3161db46d5c482..5322f6357a01b0a3e01e1d58a8d943113b942562 100644 (file)
@@ -10,6 +10,8 @@ package org.opendaylight.controller.config.persist.storage.file.xml;
 
 import com.google.common.base.Charsets;
 import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.nio.file.Files;
 import java.util.List;
 import java.util.SortedSet;
@@ -29,6 +31,8 @@ public class FileStorageAdapterTest {
 
     private static int i;
     private File file;
+    private static final String NON_EXISTENT_DIRECTORY = "./nonExistentDir/";
+    private static final String NON_EXISTENT_FILE = "nonExistent.txt";
 
     @Before
     public void setUp() throws Exception {
@@ -39,6 +43,32 @@ public class FileStorageAdapterTest {
         i = 1;
     }
 
+    @Test
+    public void testNewFile() throws Exception {
+        XmlFileStorageAdapter storage = new XmlFileStorageAdapter();
+        PropertiesProviderTest pp = new PropertiesProviderTest();
+        pp.addProperty("fileStorage",NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE);
+        pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
+        storage.instantiate(pp);
+
+        final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
+            @Override
+            public String getConfigSnapshot() {
+                return createConfig();
+            }
+
+            @Override
+            public SortedSet<String> getCapabilities() {
+                return createCaps();
+            }
+        };
+        storage.persistConfig(holder);
+
+        storage.persistConfig(holder);
+
+        Assert.assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]");
+        delete(new File(NON_EXISTENT_DIRECTORY));
+    }
     @Test
     public void testFileAdapter() throws Exception {
         XmlFileStorageAdapter storage = new XmlFileStorageAdapter();
@@ -191,4 +221,12 @@ public class FileStorageAdapterTest {
         return "<config>" + i++ + "</config>";
     }
 
+    private void delete(File f) throws IOException {
+        if (f.isDirectory()) {
+            for (File c : f.listFiles())
+                delete(c);
+        }
+        if (!f.delete())
+            throw new FileNotFoundException("Failed to delete file: " + f);
+    }
 }
index dca781e7ec403d2f9b4968eed59e4003b8d6b2ac..28637bcf46d1f2ae64f7c9cde5c4ab8026f18f30 100644 (file)
          <dependency>
           <groupId>org.opendaylight.yangtools</groupId>
           <artifactId>yang-binding</artifactId>
-          <version>0.6.1</version>
+          <version>${yangtools.version}</version>
          </dependency>
          <dependency>
           <groupId>org.opendaylight.yangtools</groupId>
           <artifactId>binding-type-provider</artifactId>
-          <version>0.6.1</version>
+          <version>${yangtools.version}</version>
          </dependency>
          <dependency>
           <groupId>org.opendaylight.yangtools</groupId>
index 47563b94cfe177cf8bab8e8c20d00436d422b87d..1ddfe1c7f354d23162353e2dbaa046c8ea281c7d 100644 (file)
@@ -13,7 +13,7 @@ osgi.bundles=\
     reference\:file\:../lib/jersey-server-1.17.jar@2:start
 
 # Netconf startup configuration
-netconf.tcp.address=0.0.0.0
+netconf.tcp.address=127.0.0.1
 netconf.tcp.port=8383
 
 netconf.tcp.client.address=127.0.0.1
index c1e2fecedd2ca3daf1e5dac2722ec7649442e3cd..e6cfee15e1501de716e43fa4a1ff80f0138e0434 100644 (file)
@@ -72,7 +72,7 @@
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                        <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index 1686cad3de0aacc365bcc195acc16314180cbb51..6d1405019c28c2fc116bd702fcdf94c562832c8e 100644 (file)
@@ -73,38 +73,46 @@ module opendaylight-meter-types {
         choice band-type {
             case drop {
                 leaf drop-rate {
+                    description "Rate for dropping packets";
                     type uint32;
                 }
                 
                 leaf drop-burst-size {
+                    description "Size of bursts";
                     type uint32;
                 }
             }
 
             case dscp-remark {
                 leaf dscp-remark-rate {
+                    description "Rate for remarking packets";
                     type uint32;
                 }
                 
                 leaf dscp-remark-burst-size {
+                    description "Size of bursts";
                     type uint32;
                 }
                 
                 leaf perc_level {
+                    description "Number of drop precedence level to add";
                     type uint8;
                 }
             }
             
             case experimenter {
                 leaf experimenter-rate {
+                    description "Rate for remarking packets";
                     type uint32;
                 }
                 
                 leaf experimenter-burst-size {
+                    description "Size of bursts";
                     type uint32;
                 }
                 
                 leaf experimenter {
+                    description "Experimenter id";
                     type uint32;
                 }
             }
@@ -118,22 +126,27 @@ module opendaylight-meter-types {
     grouping meter {
         
         leaf flags {
+           description "Meter configuration flags";
            type meter-flags;        
         }
         
         leaf meter-id {
+            description "Meter instance";
             type meter-id;
         }       
         
         leaf barrier {
+            description "If true, barrier message is sent";
             type boolean; 
         }
         
         leaf meter-name {
+            description "Name of meter instance";
             type string;
         }
         
         leaf container-name {
+            description "Name of container";
             type string; 
         }
         
@@ -141,20 +154,24 @@ module opendaylight-meter-types {
             list meter-band-header {
                 key "band-id";
                 leaf band-id {
+                    description "Meter band id";
                     type band-id;
                 }
                 
                 container meter-band-types {
                     leaf flags {
+                        description "Meter band flags";
                         type meter-band-type;
                     }
                 }
             
                 leaf band-rate {
+                    description "Rate for this band";
                     type uint32;
                 }
         
                 leaf band-burst-size {
+                    description "Size of bursts";
                     type uint32;
                 }
                 uses band-type;
index 521ec23859e0656ed15bb6db2e7095bbcafbf89c..674ea240ebc164af1ff77036264dbad5f35b70d3 100644 (file)
     </profiles>
 
     <properties>
-        <yangtools.version>0.6.1</yangtools.version>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
         <!-- Java Versions -->
index ea50e943cad406cfcfd8fc7c7273473ad43bd6c2..e5a74e42a155fee7a587890fc91b0b9d3e4a9b12 100644 (file)
@@ -56,7 +56,7 @@
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                       <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index aec9fe4e332c9c8b843eb768c22454d953c2b44d..d87e272032e5f5d47f1b53e0c2cb24bc2c8153b7 100644 (file)
@@ -69,7 +69,7 @@
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                       <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index 437051e3468abc4ae96b5473f3304ed4846f8e99..5dd08d062d0159dfc18a7d4f11338c47505fb2a1 100644 (file)
@@ -26,7 +26,6 @@
         <dependency>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>concepts</artifactId>
-            <version>0.6.1</version>
         </dependency>
         <dependency>
             <groupId>org.osgi</groupId>
index 2ec66b57a3a0d1a661d20964a2c3b213ae83834a..3a9b00dce079994d1351142a3f288ffbacf631fc 100644 (file)
@@ -21,7 +21,6 @@
     <dependency>
       <groupId>org.opendaylight.yangtools</groupId>
       <artifactId>concepts</artifactId>
-      <version>0.6.1</version>
     </dependency>
     <dependency>
       <groupId>com.google.guava</groupId>
index 76d80d15f704558a0d4f61dabbe41e7320ad56e2..d7b0296ce1d2ac761a371b948273f903b2c45cf8 100644 (file)
@@ -59,7 +59,7 @@
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                        <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index 5b883d7c4270b0044abb8595ad1a74187d4af856..8b193e03aa4620bcbfe1b98602488b53a49d84b9 100644 (file)
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                        <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index 37236718ef2bece67ead234c67cab65360283eb4..cc44613e448ad520063120f31c481e987f032ee5 100644 (file)
@@ -85,7 +85,7 @@ class DataReaderRouter extends AbstractDataReadRouter<InstanceIdentifier, Compos
             val simpleNode = node.getSimpleNodesByName(keyValue.key);
             if(simpleNode !== null && !simpleNode.empty) {
                 checkState(simpleNode.size <= 1,"Only one simple node for key $s is allowed in node $s",keyValue.key,node);
-                checkState(simpleNode.get(0).value == keyValue.value,"Key node must equals to instance identifier value");
+                checkState(simpleNode.get(0).value == keyValue.value,"Key node must equal to instance identifier value in node $s",node);
                 ret.put(keyValue.key,simpleNode.get(0));
             }
             val compositeNode = node.getCompositesByName(keyValue.key);
index f90c966ba3e5d938a1309bb568454c084b2ea99b..597b02ebb5d1f480e041146507075bfd61735a3b 100644 (file)
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                       <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
index cedc0d4d8fa85e3d6e336276388457aee18e6884..a04baaa91298ccf218c74958d76596c89545b204 100644 (file)
@@ -7,18 +7,9 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.connector.netconf;
 
+import com.google.common.net.InetAddresses;
 import io.netty.channel.EventLoopGroup;
 import io.netty.util.concurrent.GlobalEventExecutor;
-
-import java.io.File;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import javax.net.ssl.SSLContext;
-
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.client.NetconfSshClientDispatcher;
 import org.opendaylight.controller.netconf.util.handler.ssh.authentication.AuthenticationHandler;
@@ -31,17 +22,25 @@ import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingPr
 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
 import org.osgi.framework.BundleContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-import static com.google.common.base.Preconditions.*;
+import java.io.File;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 
-import com.google.common.base.Optional;
-import com.google.common.net.InetAddresses;
+import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
+import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
 
 /**
 *
 */
 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
 {
+    private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
 
     private static ExecutorService GLOBAL_PROCESSING_EXECUTOR = null;
     private static AbstractCachingSchemaSourceProvider<String, InputStream> GLOBAL_NETCONF_SOURCE_PROVIDER = null;
@@ -56,14 +55,20 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     }
 
     @Override
-    public void validate(){
-        super.validate();
-        checkState(getAddress() != null,"Address must be set.");
+    protected void customValidation() {
+        checkNotNull(getAddress(), addressJmxAttribute);
         //checkState(getAddress().getIpv4Address() != null || getAddress().getIpv6Address() != null,"Address must be set.");
-        checkState(getPort() != null,"Port must be set.");
-        checkState(getDomRegistry() != null,"Dom Registry must be provided.");
-    }
+        checkNotNull(getPort(), portJmxAttribute);
+        checkNotNull(getDomRegistry(), portJmxAttribute);
+        checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
+
+        checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
+        checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
 
+        checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
+        checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
+
+    }
 
     @Override
     public java.lang.AutoCloseable createInstance() {
@@ -71,10 +76,15 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         getDomRegistryDependency();
         NetconfDevice device = new NetconfDevice(getIdentifier().getInstanceName());
         String addressValue = getAddress();
-        
-        
-        int attemptMsTimeout = 60*1000;
-        int connectionAttempts = 5;
+
+        Long connectionAttempts;
+        if (getMaxConnectionAttempts() != null && getMaxConnectionAttempts() > 0) {
+            connectionAttempts = getMaxConnectionAttempts();
+        } else {
+            logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
+            connectionAttempts = null;
+        }
+        long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
         /*
          * Uncomment after Switch to IP Address
         if(getAddress().getIpv4Address() != null) {
@@ -83,8 +93,12 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
             addressValue = getAddress().getIpv6Address().getValue();
         }
         */
-        ReconnectStrategy strategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, attemptMsTimeout, 1000, 1.0, null,
-                Long.valueOf(connectionAttempts), null);
+        double sleepFactor = 1.0;
+        int minSleep = 1000;
+        Long maxSleep = null;
+        Long deadline = null;
+        ReconnectStrategy strategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, getBetweenAttemptsTimeoutMillis(),
+                minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
         
         device.setReconnectStrategy(strategy);
         
@@ -96,7 +110,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         
         device.setSocketAddress(socketAddress);
         device.setEventExecutor(getEventExecutorDependency());
-        device.setDispatcher(createDispatcher());
+        device.setDispatcher(createDispatcher(clientConnectionTimeoutMillis));
         device.setSchemaSourceProvider(getGlobalNetconfSchemaProvider(bundleContext));
         
         getDomRegistryDependency().registerProvider(device, bundleContext);
@@ -124,14 +138,14 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         return GLOBAL_NETCONF_SOURCE_PROVIDER;
     }
 
-    private NetconfClientDispatcher createDispatcher() {
+    private NetconfClientDispatcher createDispatcher(long clientConnectionTimeoutMillis) {
         EventLoopGroup bossGroup = getBossThreadGroupDependency();
         EventLoopGroup workerGroup = getWorkerThreadGroupDependency();
         if(getTcpOnly()) {
-            return new NetconfClientDispatcher( bossGroup, workerGroup);
+            return new NetconfClientDispatcher( bossGroup, workerGroup, clientConnectionTimeoutMillis);
         } else {
             AuthenticationHandler authHandler = new LoginPassword(getUsername(),getPassword());
-            return new NetconfSshClientDispatcher(authHandler , bossGroup, workerGroup);
+            return new NetconfSshClientDispatcher(authHandler , bossGroup, workerGroup, clientConnectionTimeoutMillis);
         }
     }
 
index 233151687797ce46e880f146d9f89e118e71f3ae..b28e72eb80251adb294d99f2e72d17c7edd7cbaf 100644 (file)
@@ -88,6 +88,25 @@ module odl-sal-netconf-connector-cfg {
                     }
                 }
             }
+
+            leaf connection-timeout-millis {
+                description "Specifies timeout in milliseconds after which connection must be established.";
+                type uint32;
+                default 5000;
+            }
+
+            leaf max-connection-attempts {
+                description "Maximum number of connection retries. Non positive value or null is interpreted as infinity.";
+                type uint32;
+                default 0; // retry forever
+            }
+
+
+            leaf between-attempts-timeout-millis {
+                description "Timeout in milliseconds to wait between connection attempts.";
+                type uint16;
+                default 10000;
+            }
         }
     }
 }
\ No newline at end of file
index 619b42be054d1637f00877b54525719e244a416b..ae31c2382fa82b3a9901bdbc4cfdb9be07c3f815 100644 (file)
                     <dependency>
                         <groupId>org.opendaylight.yangtools</groupId>
                         <artifactId>maven-sal-api-gen-plugin</artifactId>
-                        <version>0.6.1</version>
+                       <version>${yangtools.version}</version>
                         <type>jar</type>
                     </dependency>
                 </dependencies>
diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft01.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft01.java
deleted file mode 100644 (file)
index 557adb6..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.api;
-
-public class Draft01 {
-    public static class MediaTypes {
-        public static final String API = "application/vnd.yang.api";
-        public static final String DATASTORE = "application/vnd.yang.datastore";
-        public static final String DATA = "application/vnd.yang.data";
-        public static final String EVENT = "application/vnd.yang.event";
-        public static final String OPERATION = "application/vnd.yang.operation";
-        public static final String PATCH = "application/vnd.yang.patch";
-    }
-}
index 60a8f285a2cc17188dcd4ea1cbb25055bb171a81..848f2c48ab10e2fb12ea4ca9c67481a5f65b6528 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.rest.api;
 
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
@@ -23,33 +24,28 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
  *   The URI hierarchy for the RESTCONF resources consists of an entry
- *   point container, 3 top-level resources, and 1 field.  Refer to
- *  Section 5 for details on each URI.
- *    <ul>
+ *   point container, 4 top-level resources, and 1 field.
+ *   <ul>
  *    <li><b>/restconf</b> - {@link #getRoot()}
- *     <ul><li><b>/config</b> 
- *         <li><b>/operational</b> - {@link #readAllData()} - Added in Draft02
- *         <li><b>/datastore</b> - {@link #readAllData()}
- *         <ul>
- *            <li>/(top-level-data-nodes) (config=true or false)
- *         </ul>
- *         <li>/modules
- *          <ul><li>/module
- *              <li>/name
- *              <li>/revision
- *              <li>/namespace
- *              <li>/feature
- *             <li>/deviation
- *          </ul>
- *          <li>/operations
- *          <ul>
- *             <li>/(custom protocol operations)
- *          </ul>
- *         <li>/version (field)
+ *     <ul>
+ *      <li><b>/config</b> - {@link #readConfigurationData(String)} 
+ *                              {@link #updateConfigurationData(String, CompositeNode)}
+ *                              {@link #createConfigurationData(CompositeNode)}
+ *                              {@link #createConfigurationData(String, CompositeNode)}
+ *                              {@link #deleteConfigurationData(String)}
+ *      <li><b>/operational</b> - {@link #readOperationalData(String)} 
+ *      <li>/modules - {@link #getModules()}
+ *       <ul>
+ *        <li>/module
+ *       </ul>
+ *      <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)}
+ *                               {@link #invokeRpc(String, CompositeNode)}
+ *      <li>/version (field)
  *     </ul>
+ *   </ul>
  */
 @Path("/")
-public interface RestconfService extends RestconfServiceLegacy {
+public interface RestconfService {
 
     public static final String XML = "+xml";
     public static final String JSON = "+json";
@@ -59,26 +55,25 @@ public interface RestconfService extends RestconfServiceLegacy {
 
     @GET
     @Path("/modules")
-    @Produces({Draft01.MediaTypes.API+JSON,Draft01.MediaTypes.API+XML,
-               Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
+    @Produces({Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
     public StructuredData getModules();
 
     @POST
     @Path("/operations/{identifier}")
-    @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-               Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML, 
+    @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
                MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-               Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML, 
+    @Consumes({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
                MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
     public StructuredData invokeRpc(@PathParam("identifier") String identifier, CompositeNode payload);
     
     @POST
     @Path("/operations/{identifier}")
-    @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-               Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML, 
+    @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
+               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
                MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData invokeRpc(@PathParam("identifier") String identifier);
+    public StructuredData invokeRpc(@PathParam("identifier") String identifier, @DefaultValue("") String noPayload);
     
     @GET
     @Path("/config/{identifier:.+}")
diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfServiceLegacy.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfServiceLegacy.java
deleted file mode 100644 (file)
index 7d6cbfe..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.api;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.opendaylight.controller.sal.restconf.impl.StructuredData;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-public interface RestconfServiceLegacy {
-
-    public static final String XML = "+xml";
-    public static final String JSON = "+json";
-    
-    @Deprecated
-    @GET
-    @Path("/datastore")
-    @Produces({Draft01.MediaTypes.DATASTORE+JSON,Draft01.MediaTypes.DATASTORE+XML})
-    public StructuredData readAllData();
-
-    @Deprecated
-    @GET
-    @Path("/datastore/{identifier:.+}")
-    @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML, 
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData readData(@PathParam("identifier") String identifier);
-
-    @Deprecated
-    @POST
-    @Path("/datastore/{identifier:.+}")
-    @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML, 
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public Response createConfigurationDataLegacy(@PathParam("identifier") String identifier, CompositeNode payload);
-
-    @Deprecated
-    @PUT
-    @Path("/datastore/{identifier:.+}")
-    @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML, 
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public Response updateConfigurationDataLegacy(@PathParam("identifier") String identifier, CompositeNode payload);
-
-}
index f3995707f3961c53e0fa4f19139731f75543a983..0d73485c80b3fcbceaddf7235d93737cad9fa40c 100644 (file)
@@ -20,13 +20,12 @@ import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.Provider;
 
-import org.opendaylight.controller.sal.rest.api.Draft01;
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 @Provider
-@Consumes({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
+@Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
         MediaType.APPLICATION_JSON })
 public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
index e4c49932446e0db714ed0fb0f82264a24b7bb8b5..22e08d97f476679e5103779ccb6d6cec3a4d04fa 100644 (file)
@@ -21,7 +21,6 @@ import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.MessageBodyWriter;
 import javax.ws.rs.ext.Provider;
 
-import org.opendaylight.controller.sal.rest.api.Draft01;
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.ResponseException;
@@ -32,7 +31,7 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import com.google.gson.stream.JsonWriter;
 
 @Provider
-@Produces({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
+@Produces({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
         MediaType.APPLICATION_JSON })
 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
index bbe156d3c4c9acb32e262ecf585f8642e89911d0..b6d8c953a9219a6c9b7b59cb0128c9b8b2ee98ae 100644 (file)
@@ -26,7 +26,6 @@ import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
 
-import org.opendaylight.controller.sal.rest.api.Draft01;
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.ResponseException;
@@ -38,7 +37,7 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 
 @Provider
-@Produces({ Draft01.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
+@Produces({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
         MediaType.APPLICATION_XML, MediaType.TEXT_XML })
 public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
index f03431291ebe28c62fec8e6e9842d2556c3878af..13d617031ad5717367ee50778c692ccfbda3fb16 100644 (file)
@@ -21,14 +21,13 @@ import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.Provider;
 import javax.xml.stream.XMLStreamException;
 
-import org.opendaylight.controller.sal.rest.api.Draft01;
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.ResponseException;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 @Provider
-@Consumes({ Draft01.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
+@Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
         MediaType.APPLICATION_XML, MediaType.TEXT_XML })
 public enum XmlToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
index 07fb05adedec803c8fdf41773b03fe9ca83e19e3..cbfc3edf2cbf10ba164820aba15aa82749f0dbdd 100644 (file)
@@ -58,12 +58,6 @@ class RestconfImpl implements RestconfService {
         return INSTANCE
     }
 
-    override readAllData() {
-
-        //        return broker.readOperationalData("".toInstanceIdentifier.getInstanceIdentifier);
-        throw new UnsupportedOperationException("Reading all data is currently not supported.")
-    }
-
     override getModules() {
         throw new UnsupportedOperationException("TODO: auto-generated method stub")
     }
@@ -76,7 +70,10 @@ class RestconfImpl implements RestconfService {
         return callRpc(identifier.rpcDefinition, payload)
     }
 
-    override invokeRpc(String identifier) {
+    override invokeRpc(String identifier, String noPayload) {
+        if (!noPayload.nullOrEmpty) {
+            throw new ResponseException(UNSUPPORTED_MEDIA_TYPE, "Content-Type contains unsupported Media Type.");
+        }
         return callRpc(identifier.rpcDefinition, null)
     }
 
@@ -103,17 +100,6 @@ class RestconfImpl implements RestconfService {
         return new StructuredData(rpcResult.result, rpc.output, null)
     }
 
-    override readData(String identifier) {
-        val iiWithData = identifier.toInstanceIdentifier
-        var CompositeNode data = null;
-        if (iiWithData.mountPoint !== null) {
-            data = broker.readOperationalDataBehindMountPoint(iiWithData.mountPoint, iiWithData.instanceIdentifier)
-        } else {
-            data = broker.readOperationalData(iiWithData.getInstanceIdentifier);
-        }
-        return new StructuredData(data, iiWithData.schemaNode, iiWithData.mountPoint)
-    }
-
     override readConfigurationData(String identifier) {
         val iiWithData = identifier.toInstanceIdentifier
         var CompositeNode data = null;
@@ -136,10 +122,6 @@ class RestconfImpl implements RestconfService {
         return new StructuredData(data, iiWithData.schemaNode, iiWithData.mountPoint)
     }
 
-    override updateConfigurationDataLegacy(String identifier, CompositeNode payload) {
-        updateConfigurationData(identifier, payload);
-    }
-
     override updateConfigurationData(String identifier, CompositeNode payload) {
         val iiWithData = identifier.toInstanceIdentifier
         val value = normalizeNode(payload, iiWithData.schemaNode, iiWithData.mountPoint)
@@ -156,10 +138,6 @@ class RestconfImpl implements RestconfService {
         }
     }
 
-    override createConfigurationDataLegacy(String identifier, CompositeNode payload) {
-        createConfigurationData(identifier, payload);
-    }
-
     override createConfigurationData(String identifier, CompositeNode payload) {
         if (payload.namespace === null) {
             throw new ResponseException(BAD_REQUEST,
index 318159063ab481454298b738d3fc8ceb18b7fdff..874e8b0d1f8f5e7cf151a4c548624b01d72576a5 100644 (file)
@@ -21,7 +21,6 @@ import java.util.Set;
 import javax.ws.rs.WebApplicationException;
 
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
@@ -52,7 +51,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
      * Test of json output when as input are specified composite node with empty
      * data + YANG file
      */
-    @Ignore
+
     @Test
     public void compositeNodeAndYangWithJsonReaderEmptyDataTest() {
         CompositeNode compositeNode = prepareCompositeNodeWithEmpties();
@@ -540,49 +539,49 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
                 TestUtils.buildQName("cont1", "simple:yang:types", "2013-11-5"), null, null, ModifyAction.CREATE, null);
 
         // lst11_1
-        MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+        MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
                 null, ModifyAction.CREATE, null);
         cont1.getChildren().add(lst11_1);
 
-        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_1,
+        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_1,
                 (short) 1, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(lf111_1);
 
         // lst111_1_1
-        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
                 lst11_1, null, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(lst111_1_1);
-        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111"),
+        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
                 lst111_1_1, (int) 34, ModifyAction.CREATE, null);
         lst111_1_1.getChildren().add(lf1111_1_1);
         lst111_1_1.init();
         // :lst111_1_1
 
         // lst111_1_2
-        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
                 lst11_1, null, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(lst111_1_2);
-        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111"),
+        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
                 lst111_1_2, (int) 35, ModifyAction.CREATE, null);
         lst111_1_2.getChildren().add(lf1111_1_2);
         lst111_1_2.init();
         // :lst111_1_2
 
         // lst111_1_3
-        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
                 lst11_1, null, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(lst111_1_3);
         lst111_1_2.init();
         // :lst111_1_3
 
         // lst111_1_4
-        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111"),
+        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
                 lst11_1, null, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(lst111_1_4);
         lst111_1_2.init();
         // :lst111_1_4
 
-        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
                 lst11_1, null, ModifyAction.CREATE, null);
         lst11_1.getChildren().add(cont111_1);
 
@@ -590,39 +589,39 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         // :lst11_1
 
         // lst11_2
-        MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+        MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
                 null, ModifyAction.CREATE, null);
         cont1.getChildren().add(lst11_2);
 
-        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_2,
+        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_2,
                 (short) 2, ModifyAction.CREATE, null);
         lst11_2.getChildren().add(lf111_2);
 
         // cont111_2
-        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
                 lst11_2, null, ModifyAction.CREATE, null);
         lst11_2.getChildren().add(cont111_2);
 
-        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111"),
+        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
                 cont111_2, (int) 1024, ModifyAction.CREATE, null);
         cont111_2.getChildren().add(lflst1111_2_2);
-        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111"),
+        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
                 cont111_2, (int) 4096, ModifyAction.CREATE, null);
         cont111_2.getChildren().add(lflst1111_2_3);
 
         // lst1111_2
-        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
                 cont111_2, null, ModifyAction.CREATE, null);
         cont111_2.getChildren().add(lst1111_2_1);
-        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B"),
+        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B","simple:yang:types","2013-11-5"),
                 lst1111_2_1, (short) 4, ModifyAction.CREATE, null);
         lst1111_2_1.getChildren().add(lf1111B_2_1);
         lst1111_2_1.init();
 
-        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
                 cont111_2, null, ModifyAction.CREATE, null);
         cont111_2.getChildren().add(lst1111_2_2);
-        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A"),
+        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A","simple:yang:types","2013-11-5"),
                 lst1111_2_2, "lf1111A str12", ModifyAction.CREATE, null);
         lst1111_2_2.getChildren().add(lf1111A_2_2);
         lst1111_2_2.init();
@@ -631,7 +630,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         cont111_2.init();
         // :cont111_2
 
-        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112"), lst11_2,
+        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112","simple:yang:types","2013-11-5"), lst11_2,
                 null, ModifyAction.CREATE, null);
         lst11_2.getChildren().add(lst112_2);
         lst112_2.init();
@@ -640,25 +639,25 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         // :lst11_2
 
         // lst11_3
-        MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11"), cont1,
+        MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
                 null, ModifyAction.CREATE, null);
         cont1.getChildren().add(lst11_3);
 
-        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111"), lst11_3,
+        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_3,
                 (short) 3, ModifyAction.CREATE, null);
         lst11_3.getChildren().add(lf111_3);
 
         // cont111_3
-        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111"),
+        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
                 lst11_3, null, ModifyAction.CREATE, null);
         lst11_3.getChildren().add(cont111_3);
 
-        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
                 cont111_3, null, ModifyAction.CREATE, null);
         cont111_3.getChildren().add(lst1111_3_1);
         lst1111_3_1.init();
 
-        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111"),
+        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
                 cont111_3, null, ModifyAction.CREATE, null);
         cont111_3.getChildren().add(lst1111_3_2);
         lst1111_3_2.init();
index 392f444cf2def8ae783c4dba0fa95b0d740746d3..745f11c210db6c44f90ba97ccacfd6624dc1eb4e 100644 (file)
@@ -17,13 +17,15 @@ import java.util.regex.Pattern;
 import javax.ws.rs.WebApplicationException;
 
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
 public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
@@ -33,7 +35,6 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
         dataLoad("/cnsn-to-json/identityref", 2, "identityref-module", "cont");
     }
 
-    @Ignore
     @Test
     public void identityrefToJsonTest() {
         String json = null;
@@ -53,7 +54,6 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
         assertTrue(mtch.matches());
     }
 
-    @Ignore
     @Test
     public void identityrefToJsonWithoutQNameTest() {
         String json = null;
@@ -74,13 +74,13 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     private CompositeNode prepareCompositeNode(Object value) {
-        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont","identityref:module","2013-12-2"), null, null,
                 ModifyAction.CREATE, null);
-        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1"), cont, null,
+        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1","identityref:module","2013-12-2"), cont, null,
                 ModifyAction.CREATE, null);
         cont.getChildren().add(cont1);
 
-        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1"), cont1, value,
+        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1","identityref:module","2013-12-2"), cont1, value,
                 ModifyAction.CREATE, null);
 
         cont1.getChildren().add(lf1);
index d1dca95f43418c4e4a1e34b820ae4e67f6aeeee0..17d7fe6be09eaa18f48ac5831527fc58076dbe18 100644 (file)
@@ -20,8 +20,13 @@ import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.*;
-import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyType;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -39,20 +44,13 @@ public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLo
         dataLoad("/cnsn-to-json/simple-data-types");
     }
 
-    // FIXME
-    @Ignore
     @Test
-    public void incorrectTopLevelElementTest() {
-
+    public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
         String jsonOutput = null;
-        try {
-            jsonOutput = TestUtils
-                    .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
-                            (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(),
-                            StructuredDataToJsonProvider.INSTANCE);
-        } catch (WebApplicationException | IOException e) {
-            LOG.error("WebApplicationException or IOException was raised");
-        }
+        jsonOutput = TestUtils
+                .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+                        (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(),
+                        StructuredDataToJsonProvider.INSTANCE);
         assertNotNull(jsonOutput);
         assertTrue(jsonOutput.contains("\"lf1\": \"\""));
     }
index 54664ae069a98e8ccc7dc120767e0e74dd570ec2..348edbd2945d6d1fb2f86ea0d1e3026a81132c47 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
-import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -18,40 +17,38 @@ import java.util.regex.Pattern;
 import javax.ws.rs.WebApplicationException;
 
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
 public class CnSnToJsonWithDataFromSeveralModulesTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
     public static void initialize() {
-        dataLoad("/xml-to-cnsn/data-of-several-modules/yang",2,"module1","cont_m1");
+        dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
     }
 
-    @Ignore
     @Test
     public void dataFromSeveralModulesToJsonTest() throws WebApplicationException, IOException, URISyntaxException {
         SchemaContext schemaContext = TestUtils.loadSchemaContext(modules);
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
                 StructuredDataToJsonProvider.INSTANCE);
 
-//         String output =
-//         String.format("\"data\"   :   {\n" +
-//                             "\t\"cont_m1\"   :  {\n" +
-//                                 "\t\t\"lf1_m1\"   :  \"lf1 m1 value\"\n" +
-//                             "\t}\n" +
-//                             "\t\"cont_m2\"   :  {\n" +
-//                                 "\t\t\"lf1_m2\"   :  \"lf1 m2 value\"\n" +
-//                             "\t}\n" +
-//                     "}");
+        // String output =
+        // String.format("\"data\"   :   {\n" +
+        // "\t\"cont_m1\"   :  {\n" +
+        // "\t\t\"lf1_m1\"   :  \"lf1 m1 value\"\n" +
+        // "\t}\n" +
+        // "\t\"cont_m2\"   :  {\n" +
+        // "\t\t\"lf1_m2\"   :  \"lf1 m2 value\"\n" +
+        // "\t}\n" +
+        // "}");
 
         StringBuilder regex = new StringBuilder();
         regex.append("^");
@@ -59,27 +56,27 @@ public class CnSnToJsonWithDataFromSeveralModulesTest extends YangAndXmlAndDataS
         regex.append(".*\"data\"");
         regex.append(".*:");
         regex.append(".*\\{");
-        
-        regex.append(".*\"contB_m1\"");
+
+        regex.append(".*\"cont_m1\"");
         regex.append(".*:");
         regex.append(".*\\{");
         regex.append(".*\\}");
-        
-        regex.append(".*\"cont_m1\"");
+
+        regex.append(".*\"contB_m1\"");
         regex.append(".*:");
         regex.append(".*\\{");
         regex.append(".*\\}");
 
-        regex.append(".*\"contB_m2\"");
+        regex.append(".*\"cont_m2\"");
         regex.append(".*:");
         regex.append(".*\\{");
         regex.append(".*\\}");
-        
-        regex.append(".*\"cont_m2\"");
+
+        regex.append(".*\"contB_m2\"");
         regex.append(".*:");
         regex.append(".*\\{");
         regex.append(".*\\}");
-        
+
         regex.append(".*\\}");
 
         regex.append(".*");
@@ -93,24 +90,44 @@ public class CnSnToJsonWithDataFromSeveralModulesTest extends YangAndXmlAndDataS
     }
 
     private CompositeNode prepareCnSn() throws URISyntaxException {
-        CompositeNodeWrapper data = new CompositeNodeWrapper(new URI("urn:ietf:params:xml:ns:netconf:base:1.0"), "data");
-
-        URI uriModule1 = new URI("module:one");
-        CompositeNodeWrapper cont_m1 = new CompositeNodeWrapper(uriModule1, "cont_m1");
-        SimpleNodeWrapper lf1_m1 = new SimpleNodeWrapper(uriModule1, "lf1_m1", "lf1 m1 value");
-        cont_m1.addValue(lf1_m1);
-        CompositeNodeWrapper contB_m1 = new CompositeNodeWrapper(uriModule1, "contB_m1");
-        
-        data.addValue(contB_m1);
-        data.addValue(cont_m1);
-
-        URI uriModule2 = new URI("module:two");
-        CompositeNodeWrapper cont_m2 = new CompositeNodeWrapper(uriModule2, "cont_m2");
-        SimpleNodeWrapper lf1_m2 = new SimpleNodeWrapper(uriModule2, "lf1_m2", "lf1 m2 value");
-        cont_m2.addValue(lf1_m2);
-        CompositeNodeWrapper contB_m2 = new CompositeNodeWrapper(uriModule2, "contB_m2");
-        data.addValue(contB_m2);
-        data.addValue(cont_m2);
+        String uri1 = "module:one";
+        String rev1 = "2014-01-17";
+
+        MutableCompositeNode data = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("data", "urn:ietf:params:xml:ns:netconf:base:1.0", "2000-01-01"), null, null,
+                null, null);
+
+        MutableCompositeNode cont_m1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont_m1", uri1, rev1), data, null, null, null);
+        data.getChildren().add(cont_m1);
+
+        MutableSimpleNode<?> lf1_m1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m1", uri1, rev1),
+                cont_m1, "lf1 m1 value", null, null);
+        cont_m1.getChildren().add(lf1_m1);
+        cont_m1.init();
+
+        MutableCompositeNode contB_m1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("contB_m1", uri1, rev1), data, null, null, null);
+        data.getChildren().add(contB_m1);
+        contB_m1.init();
+
+        String uri2 = "module:two";
+        String rev2 = "2014-01-17";
+        MutableCompositeNode cont_m2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont_m2", uri2, rev2), data, null, null, null);
+        data.getChildren().add(cont_m2);
+
+        MutableSimpleNode<?> lf1_m2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m2", uri2, rev2),
+                cont_m1, "lf1 m2 value", null, null);
+        cont_m2.getChildren().add(lf1_m2);
+        cont_m2.init();
+
+        MutableCompositeNode contB_m2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("contB_m2", uri2, rev2), data, null, null, null);
+        data.getChildren().add(contB_m2);
+        contB_m2.init();
+
+        data.init();
         return data;
     }
 
index 5a81b326ab30a130bce2c0265f425166115e60fa..92de14bba4a730406f4a58b4e738b618cc05bf3b 100644 (file)
@@ -35,7 +35,7 @@ public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoad
     
     @BeforeClass
     public static void initialization() throws URISyntaxException {
-        dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+        dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
     }
 
     @Test
index 9723af7671e41dc75fd5de5521bee3fa6606817a..18b5ce490ff137f7da978052a09819a6a5b4e1d1 100644 (file)
@@ -32,41 +32,83 @@ import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
 public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
     public static void initialize() {
-        dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+        dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
     }
 
     @Test
-    public void saveCnSnToXml() throws WebApplicationException, IOException, URISyntaxException, XMLStreamException {
-        CompositeNode cnSn = prepareCnSn();
+    public void saveCnSnToXmlTest() throws WebApplicationException, IOException, URISyntaxException, XMLStreamException {
+        CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
-        validateXmlOutput(output);
+        //uncomment for debug
         // System.out.println(output);
+        validateXmlOutput(output);
 
     }
 
     @Ignore
     @Test
-    public void saveCnSnToJson() throws WebApplicationException, IOException, URISyntaxException {
-        CompositeNode cnSn = prepareCnSn();
+    public void saveCnSnWithLeafListInstIdentifierToXmlTest() throws WebApplicationException, IOException,
+            URISyntaxException, XMLStreamException {
+        CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
+        String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
+                StructuredDataToXmlProvider.INSTANCE);
+        //uncomment for debug
+        // System.out.println(output);
+        validateXmlOutputWithLeafList(output);
+    }
+
+    @Test
+    public void saveCnSnToJsonTest() throws WebApplicationException, IOException, URISyntaxException {
+        CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToJsonProvider.INSTANCE);
-        assertTrue(output
-                .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111=\\\"value1\\\"][augment-module:keyvalue112=\\\"value2\\\"]/augment-augment-module:lf112\""));
+        boolean strInOutput = false;
+        strInOutput = output
+                .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111=\\\"value1\\\"][augment-module:keyvalue112=\\\"value2\\\"]/augment-augment-module:lf112\"");
+
+        if (!strInOutput) {
+            strInOutput = output
+                    .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111='value1'][augment-module:keyvalue112='value2']/augment-augment-module:lf112\"");
+        }
+        //uncomment for debug
         // System.out.println(output);
+        assertTrue(strInOutput);
+    }
+
+
+    @Test
+    public void saveCnSnWithLeafListInstIdentifierToJsonTest() throws WebApplicationException, IOException,
+            URISyntaxException {
+        CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
+        String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
+                StructuredDataToJsonProvider.INSTANCE);
+        //uncomment for debug
+        // System.out.println(output);
+        boolean strInOutput = false;
+        strInOutput = output
+                .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.='lflst11_1']\"");
+        if (!strInOutput) {
+            strInOutput = output
+                    .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.=\\\"lflst11_1\\\"]\"");
+        }
+
+        assertTrue(strInOutput);
     }
 
     private void validateXmlOutput(String xml) throws XMLStreamException {
@@ -106,21 +148,66 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
                 + ":lst11[" + aModulePrefix + ":keyvalue111='value1'][" + aModulePrefix + ":keyvalue112='value2']/"
                 + aaModulePrefix + ":lf112";
 
-//        System.out.println(xml);
         assertTrue(xml.contains(instanceIdentifierValue));
 
     }
 
-    private CompositeNode prepareCnSn() throws URISyntaxException {
-        CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("instance:identifier:module"), "cont");
-        CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("instance:identifier:module"), "cont1");
-        CompositeNodeWrapper lst11 = new CompositeNodeWrapper(new URI("augment:module"), "lst11");
-        InstanceIdentifier instanceIdentifier = createInstanceIdentifier();
-        SimpleNodeWrapper lf111 = new SimpleNodeWrapper(new URI("augment:augment:module"), "lf111", instanceIdentifier);
+    private void validateXmlOutputWithLeafList(String xml) throws XMLStreamException {
+        XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
+        XMLEventReader eventReader;
 
-        lst11.addValue(lf111);
-        cont1.addValue(lst11);
-        cont.addValue(cont1);
+        eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
+        String aModuleLfLstPrefix = null;
+        String iiModulePrefix = null;
+        while (eventReader.hasNext()) {
+            XMLEvent nextEvent = eventReader.nextEvent();
+            if (nextEvent.isStartElement()) {
+                StartElement startElement = (StartElement) nextEvent;
+                if (startElement.getName().getLocalPart().equals("lf111")) {
+                    Iterator prefixes = startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
+
+                    while (prefixes.hasNext() && aModuleLfLstPrefix == null) {
+                        String prefix = (String) prefixes.next();
+                        if (!prefix.isEmpty()) {
+                            aModuleLfLstPrefix = prefix;
+                        }
+                    }
+                    iiModulePrefix = startElement.getNamespaceContext().getPrefix("instance:identifier:module");
+                    break;
+                }
+            }
+        }
+
+        assertNotNull(aModuleLfLstPrefix);
+        assertNotNull(iiModulePrefix);
+
+        String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/"
+                + aModuleLfLstPrefix + ":lflst11[.='lflst11_1']";
+
+        assertTrue(xml.contains(instanceIdentifierValue));
+
+    }
+
+    private CompositeNode prepareCnSn(InstanceIdentifier instanceIdentifier) throws URISyntaxException {
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont", "instance:identifier:module", "2014-01-17"), null, null,null,null);
+        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont1", "instance:identifier:module", "2014-01-17"), cont, null,null,null);
+        MutableCompositeNode lst11 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst11", "augment:module", "2014-01-17"), cont1, null,null,null);
+
+        MutableSimpleNode<?> lf111 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111", "augment:augment:module", "2014-01-17"),
+                lst11, instanceIdentifier,null,null);
+        
+        
+        lst11.getChildren().add(lf111);
+        lst11.init();
+
+        cont1.getChildren().add(lst11);
+        cont1.init();
+        
+        cont.getChildren().add(cont1);
+        cont.init();
 
         return cont;
     }
@@ -142,4 +229,13 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         return new InstanceIdentifier(pathArguments);
     }
 
+    private InstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException {
+        List<PathArgument> pathArguments = new ArrayList<>();
+        pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
+        pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
+        pathArguments.add(new NodeWithValue(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1"));
+
+        return new InstanceIdentifier(pathArguments);
+    }
+
 }
index 2a8ab7a344964b8a99e952a6d9336d1145b35e30..e1d7e6a62447d3b1145c4bb672267ec77e4fc762 100644 (file)
@@ -72,9 +72,9 @@ public class MediaTypesTest extends JerseyTest {
       String uriPath = "ietf-interfaces:interfaces";
       String uri = createUri(uriPrefix, uriPath);
       when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-      post(uri, Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+JSON, jsonData);
+      post(uri, Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+JSON, jsonData);
       verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, Draft02.MediaTypes.DATA+XML, Draft02.MediaTypes.DATA+XML, xmlData);
+      post(uri, Draft02.MediaTypes.OPERATION+XML, Draft02.MediaTypes.OPERATION+XML, xmlData);
       verify(restconfService, times(2)).invokeRpc(eq(uriPath), any(CompositeNode.class));
       post(uri, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, jsonData);
       verify(restconfService, times(3)).invokeRpc(eq(uriPath), any(CompositeNode.class));
index 76ec65c7127f040a47ed4692c797a585a777f7d4..be7be9444cac594c8080dd99eae2c39ab5baed90 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
 import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
 
 import java.io.FileNotFoundException;
@@ -20,21 +19,16 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.logging.Level;
 
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
 
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
-import org.glassfish.jersey.test.TestProperties;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
-import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -84,24 +78,6 @@ public class RestGetOperationTest extends JerseyTest {
         return resourceConfig;
     }
 
-    /**
-     * Tests of status codes for "/datastore/{identifier}".
-     */
-    @Test
-    public void getDatastoreStatusCodes() throws FileNotFoundException, UnsupportedEncodingException {
-        mockReadOperationalDataMethod();
-        String uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
-        assertEquals(200, get(uri, MediaType.APPLICATION_XML));
-
-        uri = createUri("/datastore/", "wrong-module:interfaces/interface/eth0");
-        assertEquals(400, get(uri, MediaType.APPLICATION_XML));
-
-        // Test of request for not existing data. Returning status code 404
-        uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
-        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(null);
-        assertEquals(404, get(uri, MediaType.APPLICATION_XML));
-    }
-
     /**
      * Tests of status codes for "/operational/{identifier}".
      */
index ab63fbc547d577326db74e33eb154913ef0b779b..050aa9ab240575c8a216f8e4678787c25fdb3003 100644 (file)
@@ -14,7 +14,6 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -29,7 +28,6 @@ import java.util.concurrent.Future;
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
 
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
@@ -43,7 +41,6 @@ import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlMapper;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -153,20 +150,6 @@ public class RestPostOperationTest extends JerseyTest {
         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
     }
 
-    @Test
-    public void postDatastoreStatusCodes() throws UnsupportedEncodingException {
-        controllerContext.setSchemas(schemaContextYangsIetf);
-        mockCommitConfigurationDataPostMethod(TransactionStatus.COMMITED);
-        String uri = createUri("/datastore/", "ietf-interfaces:interfaces");
-        assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
-        mockCommitConfigurationDataPostMethod(null);
-        assertEquals(202, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
-        mockCommitConfigurationDataPostMethod(TransactionStatus.FAILED);
-        assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-    }
-
     @Test
     public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
         controllerContext.setSchemas(schemaContextYangsIetf);
index 5d7eb20c42e648a9b319329ed27792e111ae74ab..2ba4a38c88582f9cb1c4ba49a8a586024c070e37 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
-import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
 import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.createUri;
 
 import java.io.FileNotFoundException;
@@ -24,17 +23,14 @@ import java.util.concurrent.Future;
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
 
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
-import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -107,19 +103,6 @@ public class RestPutOperationTest extends JerseyTest {
         assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
     }
 
-    /**
-     * Tests of status codes for "/datastore/{identifier}".
-     */
-    @Test
-    public void putDatastoreStatusCodes() throws UnsupportedEncodingException {
-        String uri = createUri("/datastore/", "ietf-interfaces:interfaces/interface/eth0");
-        mockCommitConfigurationDataPutMethod(TransactionStatus.COMMITED);
-        assertEquals(200, put(uri, MediaType.APPLICATION_XML, xmlData));
-
-        mockCommitConfigurationDataPutMethod(TransactionStatus.FAILED);
-        assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
-    }
-
     @Test
     public void testRpcResultCommitedToStatusCodesWithMountPoint() throws UnsupportedEncodingException,
             FileNotFoundException, URISyntaxException {
@@ -131,10 +114,6 @@ public class RestPutOperationTest extends JerseyTest {
                 brokerFacade.commitConfigurationDataPutBehindMountPoint(any(MountInstance.class),
                         any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(dummyFuture);
 
-        InputStream xmlStream = RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data2.xml");
-        String xml = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
-        Entity<String> entity = Entity.entity(xml, Draft02.MediaTypes.DATA + XML);
-
         MountInstance mountInstance = mock(MountInstance.class);
         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
         MountService mockMountService = mock(MountService.class);
index e8d03fbe39193afdbbab632c4acf6d74f1bd9a76..5476d71320e9ae7a3a0fce6a9ec87f8dfe80088f 100644 (file)
@@ -26,6 +26,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 
@@ -33,7 +34,7 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch
 
     @BeforeClass
     public static void initialize() {
-        dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+        dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
     }
 
     @Test
@@ -41,7 +42,15 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch
         CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata.xml",
                 XmlToCompositeNodeProvider.INSTANCE);
         TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
-        verify(cnSn);
+        verifyListPredicate(cnSn);
+    }
+
+    @Test
+    public void loadXmlLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
+        CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata_leaf_list.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
+        TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
+        verifyLeafListPredicate(cnSn);
     }
 
     @Test
@@ -49,11 +58,40 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch
         CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata.json",
                 JsonToCompositeNodeProvider.INSTANCE);
         TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
-        verify(cnSn);
+        verifyListPredicate(cnSn);
     }
 
-    private void verify(CompositeNode cnSn) throws URISyntaxException {
-        SimpleNode<?> lf111 = getSnWithInstanceIdentifier(cnSn);
+    @Test
+    public void loadJsonLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
+        CompositeNode cnSn = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata_leaf_list.json",
+                JsonToCompositeNodeProvider.INSTANCE);
+        TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
+        verifyLeafListPredicate(cnSn);
+    }
+
+    private void verifyLeafListPredicate(CompositeNode cnSn) throws URISyntaxException {
+        SimpleNode<?> lf11 = getSnWithInstanceIdentifierWhenLeafList(cnSn);
+        Object value = lf11.getValue();
+        assertTrue(value instanceof InstanceIdentifier);
+
+        InstanceIdentifier instanceIdentifier = (InstanceIdentifier) value;
+        List<PathArgument> pathArguments = instanceIdentifier.getPath();
+        assertEquals(3, pathArguments.size());
+        String revisionDate = "2014-01-17";
+        assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), pathArguments.get(0)
+                .getNodeType());
+        assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), pathArguments.get(1)
+                .getNodeType());
+        assertEquals(TestUtils.buildQName("lflst11", "augment:module:leaf:list", "2014-01-27"), pathArguments.get(2)
+                .getNodeType());
+
+        assertTrue(pathArguments.get(2) instanceof NodeWithValue);
+        assertEquals("lflst11_1", ((NodeWithValue) pathArguments.get(2)).getValue());
+
+    }
+
+    private void verifyListPredicate(CompositeNode cnSn) throws URISyntaxException {
+        SimpleNode<?> lf111 = getSnWithInstanceIdentifierWhenList(cnSn);
         Object value = lf111.getValue();
         assertTrue(value instanceof InstanceIdentifier);
 
@@ -76,7 +114,7 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch
         assertEquals("value2", predicates.get(TestUtils.buildQName("keyvalue112", "augment:module", revisionDate)));
     }
 
-    private SimpleNode<?> getSnWithInstanceIdentifier(CompositeNode cnSn) throws URISyntaxException {
+    private SimpleNode<?> getSnWithInstanceIdentifierWhenList(CompositeNode cnSn) throws URISyntaxException {
         CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
                 "2014-01-17"));
         assertNotNull(cont1);
@@ -89,4 +127,14 @@ public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSch
         return lf111;
     }
 
+    private SimpleNode<?> getSnWithInstanceIdentifierWhenLeafList(CompositeNode cnSn) throws URISyntaxException {
+        CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
+                "2014-01-17"));
+        assertNotNull(cont1);
+        SimpleNode<?> lf11 = cont1.getFirstSimpleByName(TestUtils.buildQName("lf11", "augment:module:leaf:list",
+                "2014-01-27"));
+        assertNotNull(lf11);
+        return lf11;
+    }
+
 }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/json/jsondata_leaf_list.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/json/jsondata_leaf_list.json
new file mode 100644 (file)
index 0000000..63be4b9
--- /dev/null
@@ -0,0 +1,7 @@
+{
+    "instance-identifier-module:cont": {
+        "cont1": {
+            "augment-module-leaf-list:lf11" : "/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.=\"lflst11_1\"]"
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmldata_leaf_list.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmldata_leaf_list.xml
new file mode 100644 (file)
index 0000000..00d58c2
--- /dev/null
@@ -0,0 +1,8 @@
+<cont xmlns="instance:identifier:module">
+    <cont1>
+        <lflst11 xmlns="augment:module:leaf:list">lflst11_1</lflst11>
+        <lflst11 xmlns="augment:module:leaf:list">lflst11_2</lflst11>
+        <lflst11 xmlns="augment:module:leaf:list">lflst11_3</lflst11>
+        <lf11 xmlns:a="instance:identifier:module" xmlns:b="augment:module:leaf:list" xmlns="augment:module:leaf:list">/a:cont/a:cont1/b:lflst11[.="lflst11_1"]</lf11>
+    </cont1>
+</cont>
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/yang/augment-module-leaf-list.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/instanceidentifier/yang/augment-module-leaf-list.yang
new file mode 100644 (file)
index 0000000..54c305b
--- /dev/null
@@ -0,0 +1,20 @@
+module augment-module-leaf-list {
+  namespace "augment:module:leaf:list";  
+
+  prefix "amodulelflst";  
+  
+  import instance-identifier-module {prefix imodule; revision-date 2014-01-17;}
+   
+  revision 2014-01-27 {    
+  }
+  
+    augment "/imodule:cont/imodule:cont1" {
+       leaf-list lflst11 {
+           type string;
+       }       
+       leaf lf11 {
+            type instance-identifier;
+       }
+    }   
+         
+}
\ No newline at end of file
index 53e14ba5fbe8e1d0d945ac957b98c9e45ba65ad8..13f8cad968460d97a2f5ca7073d31745bc4a428f 100644 (file)
@@ -67,7 +67,7 @@ public class NetconfOperationServiceImplTest {
         try {
             NetconfOperationServiceImpl.checkConsistencyBetweenYangStoreAndConfig(mockJmxClient("qname1"),
                     mockYangStoreSnapshot("qname2", "qname1"));
-            fail("An exception of type " + IllegalArgumentException.class + " was expected");
+            fail("An exception of type " + IllegalStateException.class + " was expected");
         } catch (IllegalStateException e) {
             String message = e.getMessage();
             Assert.assertThat(
index 889fa8428c7fb2617e63b31653c49d0a63cf3ed0..e319d2cb679260718c9eade75234b9996170007c 100644 (file)
@@ -12,7 +12,6 @@ import org.opendaylight.controller.config.persist.api.Persister;
 import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
 import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
 import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
-import org.opendaylight.controller.netconf.client.NetconfClient;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -27,40 +26,60 @@ import java.io.IOException;
 import java.util.regex.Pattern;
 
 /**
- * Responsible for listening for notifications from netconf containing latest
+ * Responsible for listening for notifications from netconf (via JMX) containing latest
  * committed configuration that should be persisted, and also for loading last
  * configuration.
  */
 @ThreadSafe
-public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
+public class ConfigPersisterNotificationHandler implements Closeable {
 
     private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
     private final MBeanServerConnection mBeanServerConnection;
-    private final NetconfClient netconfClient;
-    private final Persister persisterAggregator;
-    private final Pattern ignoredMissingCapabilityRegex;
+    private final ConfigPersisterNotificationListener listener;
+
 
-    public ConfigPersisterNotificationHandler(MBeanServerConnection mBeanServerConnection, NetconfClient netconfClient,
+    public ConfigPersisterNotificationHandler(MBeanServerConnection mBeanServerConnection,
                                               Persister persisterAggregator, Pattern ignoredMissingCapabilityRegex) {
         this.mBeanServerConnection = mBeanServerConnection;
-        this.netconfClient = netconfClient;
-        this.persisterAggregator = persisterAggregator;
-        this.ignoredMissingCapabilityRegex = ignoredMissingCapabilityRegex;
-    }
+        listener = new ConfigPersisterNotificationListener(persisterAggregator, ignoredMissingCapabilityRegex);
+        registerAsJMXListener(mBeanServerConnection, listener);
 
-    public void init() {
-        registerAsJMXListener();
     }
 
-    private void registerAsJMXListener() {
+    private static void registerAsJMXListener(MBeanServerConnection mBeanServerConnection, ConfigPersisterNotificationListener listener) {
         logger.trace("Called registerAsJMXListener");
         try {
-            mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.objectName, this, null, null);
+            mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.objectName, listener, null, null);
         } catch (InstanceNotFoundException | IOException e) {
             throw new RuntimeException("Cannot register as JMX listener to netconf", e);
         }
     }
 
+    @Override
+    public synchronized void close() {
+        // unregister from JMX
+        ObjectName on = DefaultCommitOperationMXBean.objectName;
+        try {
+            if (mBeanServerConnection.isRegistered(on)) {
+                mBeanServerConnection.removeNotificationListener(on, listener);
+            }
+        } catch (Exception e) {
+            logger.warn("Unable to unregister {} as listener for {}", listener, on, e);
+        }
+    }
+}
+
+class ConfigPersisterNotificationListener implements NotificationListener {
+    private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class);
+
+    private final Persister persisterAggregator;
+    private final Pattern ignoredMissingCapabilityRegex;
+
+    ConfigPersisterNotificationListener(Persister persisterAggregator, Pattern ignoredMissingCapabilityRegex) {
+        this.persisterAggregator = persisterAggregator;
+        this.ignoredMissingCapabilityRegex = ignoredMissingCapabilityRegex;
+    }
+
     @Override
     public void handleNotification(Notification notification, Object handback) {
         if (notification instanceof NetconfJMXNotification == false)
@@ -92,22 +111,4 @@ public class ConfigPersisterNotificationHandler implements NotificationListener,
             throw new RuntimeException("Unable to persist configuration snapshot", e);
         }
     }
-
-    @Override
-    public synchronized void close() {
-        // unregister from JMX
-        ObjectName on = DefaultCommitOperationMXBean.objectName;
-        try {
-            if (mBeanServerConnection.isRegistered(on)) {
-                mBeanServerConnection.removeNotificationListener(on, this);
-            }
-        } catch (Exception e) {
-            logger.warn("Unable to unregister {} as listener for {}", this, on, e);
-        }
-    }
-
-    public NetconfClient getNetconfClient() {
-        return netconfClient;
-    }
-
-}
+}
\ No newline at end of file
index 0a844b69ab8a61d37d39bd11fa1a1f4bf2b37867..01d872d89cad71156b792b37dc2e78f1749f393a 100644 (file)
@@ -33,6 +33,7 @@ import java.io.InputStream;
 import java.net.InetSocketAddress;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
@@ -44,100 +45,98 @@ public class ConfigPusher {
     private static final int NETCONF_SEND_ATTEMPTS = 20;
 
     private final InetSocketAddress address;
-    private final EventLoopGroup nettyThreadgroup;
+    private final EventLoopGroup nettyThreadGroup;
 
     // Default timeout for netconf becoming stable
-    public static final long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toNanos(2);
+    public static final long DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS = TimeUnit.MINUTES.toMillis(2);
+    public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000;
     private final int delayMillis = 5000;
-    private final long timeoutNanos;
+    private final long maxWaitForCapabilitiesMillis;
+    private final long connectionTimeoutMillis;
 
-    public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup) {
-        this(address, nettyThreadgroup, DEFAULT_TIMEOUT);
+    public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup) {
+        this(address, nettyThreadGroup, DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
     }
 
-    @Deprecated
-    public ConfigPusher(InetSocketAddress address, long timeoutMillis, EventLoopGroup nettyThreadgroup) {
-        this(address, nettyThreadgroup, TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
-    }
-
-    public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup, long timeoutNanos) {
+    public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup,
+                        long maxWaitForCapabilitiesMillis, long connectionTimeoutMillis) {
         this.address = address;
-        this.nettyThreadgroup = nettyThreadgroup;
-        this.timeoutNanos = timeoutNanos;
+        this.nettyThreadGroup = nettyThreadGroup;
+        this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
+        this.connectionTimeoutMillis = connectionTimeoutMillis;
     }
 
-    public synchronized NetconfClient init(List<ConfigSnapshotHolder> configs) throws InterruptedException {
+    public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> pushConfigs(
+            List<ConfigSnapshotHolder> configs) throws InterruptedException {
         logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
-        return pushAllConfigs(configs);
-    }
 
-    private synchronized NetconfClient pushAllConfigs(List<ConfigSnapshotHolder> configs) throws InterruptedException {
         // first just make sure we can connect to netconf, even if nothing is being pushed
-        NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet(), Optional.<NetconfClient>absent());
+        {
+            NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet());
+            Util.closeClientAndDispatcher(netconfClient);
+        }
+        LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> result = new LinkedHashMap<>();
         // start pushing snapshots:
-        for (ConfigSnapshotHolder configSnapshotHolder: configs){
-            netconfClient = pushSnapshotWithRetries(configSnapshotHolder, Optional.of(netconfClient));
-            logger.debug("Config snapshot pushed successfully: {}", configSnapshotHolder);
+        for (ConfigSnapshotHolder configSnapshotHolder : configs) {
+            EditAndCommitResponseWithRetries editAndCommitResponseWithRetries = pushSnapshotWithRetries(configSnapshotHolder);
+            logger.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
+            result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
         }
-
         logger.debug("All configuration snapshots have been pushed successfully.");
-        return netconfClient;
+        return result;
     }
 
-    private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
-                                                               Optional<NetconfClient> oldClientForPossibleReuse)
+    /**
+     * Checks for ConflictingVersionException and retries until optimistic lock succeeds or maximal
+     * number of attempts is reached.
+     */
+    private synchronized EditAndCommitResponseWithRetries pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder)
             throws InterruptedException {
 
-        Exception lastException = null;
+        ConflictingVersionException lastException = null;
         int maxAttempts = 30;
-        for(int i = 0 ; i < maxAttempts; i++) {
-            NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
+
+        for (int retryAttempt = 1; retryAttempt <= maxAttempts; retryAttempt++) {
+            NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities());
             logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
             try {
-                pushLastConfig(configSnapshotHolder, netconfClient);
-                return netconfClient;
-            } catch (ConflictingVersionException | IOException e) {
-                Util.closeClientAndDispatcher(netconfClient);
+                EditAndCommitResponse editAndCommitResponse = pushLastConfig(configSnapshotHolder, netconfClient);
+                return new EditAndCommitResponseWithRetries(editAndCommitResponse, retryAttempt);
+            } catch (ConflictingVersionException e) {
                 lastException = e;
                 Thread.sleep(1000);
-            } catch (SAXException e) {
-                throw new IllegalStateException("Unable to load last config", e);
+            } catch (RuntimeException e) {
+                throw new IllegalStateException("Unable to load " + configSnapshotHolder, e);
+            } finally {
+                Util.closeClientAndDispatcher(netconfClient);
             }
         }
-        throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
-                + maxAttempts, lastException);
+        throw new IllegalStateException("Maximum attempt count has been reached for pushing " + configSnapshotHolder,
+                lastException);
     }
 
     /**
      * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
      *                     If empty set is provided, will only make sure netconf client successfuly connected to the server.
-     * @param maybeOldClient if present, close it.
      * @return NetconfClient that has all required capabilities from server.
      */
-    private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
-                                                             Optional<NetconfClient> maybeOldClient)
-            throws InterruptedException {
-
-        if (maybeOldClient.isPresent()) {
-            NetconfClient oldClient = maybeOldClient.get();
-            Util.closeClientAndDispatcher(oldClient);
-        }
+    private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps) throws InterruptedException {
 
         // TODO think about moving capability subset check to netconf client
         // could be utilized by integration tests
 
-        final long pollingStart = System.nanoTime();
-        final long deadline = pollingStart + timeoutNanos;
+        final long pollingStartNanos = System.nanoTime();
+        final long deadlineNanos = pollingStartNanos + TimeUnit.MILLISECONDS.toNanos(maxWaitForCapabilitiesMillis);
         int attempt = 0;
 
         String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
                 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
 
-        Set<String> latestCapabilities = new HashSet<>();
-        while (System.nanoTime() < deadline) {
+        Set<String> latestCapabilities = null;
+        while (System.nanoTime() < deadlineNanos) {
             attempt++;
-            NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
-                    nettyThreadgroup, additionalHeader);
+            NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadGroup,
+                    nettyThreadGroup, additionalHeader, connectionTimeoutMillis);
             NetconfClient netconfClient;
             try {
                 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
@@ -157,6 +156,10 @@ public class ConfigPusher {
             Util.closeClientAndDispatcher(netconfClient);
             Thread.sleep(delayMillis);
         }
+        if (latestCapabilities == null) {
+            logger.error("Could not connect to the server in {} ms", maxWaitForCapabilitiesMillis);
+            throw new RuntimeException("Could not connect to netconf server");
+        }
         Set<String> allNotFound = new HashSet<>(expectedCaps);
         allNotFound.removeAll(latestCapabilities);
         logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
@@ -165,70 +168,152 @@ public class ConfigPusher {
     }
 
 
-    private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
-            throws ConflictingVersionException, IOException, SAXException {
+    /**
+     * Sends two RPCs to the netconf server: edit-config and commit.
+     *
+     * @param configSnapshotHolder
+     * @param netconfClient
+     * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
+     * @throws java.lang.RuntimeException  if edit-config or commit fails otherwise
+     */
+    private synchronized EditAndCommitResponse pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
+            throws ConflictingVersionException {
 
-        Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
+        Element xmlToBePersisted;
+        try {
+            xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
+        } catch (SAXException | IOException e) {
+            throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
+        }
         logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
-        StringBuilder response = new StringBuilder("editConfig response = {");
 
-        NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
+        NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
 
         // sending message to netconf
-        NetconfMessage responseMessage = getResponse(message, netconfClient);
-
-        NetconfUtil.checkIsMessageOk(responseMessage);
-        response.append(XmlUtil.toString(responseMessage.getDocument()));
-        response.append("}");
-        responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
-
+        NetconfMessage editResponseMessage;
+        try {
+            editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, netconfClient);
+        } catch (IOException e) {
+            throw new IllegalStateException("Edit-config failed on " + configSnapshotHolder, e);
+        }
 
+        // commit
+        NetconfMessage commitResponseMessage;
+        try {
+            commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), netconfClient);
+        } catch (IOException e) {
+            throw new IllegalStateException("Edit commit succeeded, but commit failed on " + configSnapshotHolder, e);
+        }
 
-        NetconfUtil.checkIsMessageOk(responseMessage);
-        response.append("commit response = {");
-        response.append(XmlUtil.toString(responseMessage.getDocument()));
-        response.append("}");
-        logger.trace("Last configuration loaded successfully");
-        logger.trace("Detailed message {}", response);
+        if (logger.isTraceEnabled()) {
+            StringBuilder response = new StringBuilder("editConfig response = {");
+            response.append(XmlUtil.toString(editResponseMessage.getDocument()));
+            response.append("}");
+            response.append("commit response = {");
+            response.append(XmlUtil.toString(commitResponseMessage.getDocument()));
+            response.append("}");
+            logger.trace("Last configuration loaded successfully");
+            logger.trace("Detailed message {}", response);
+        }
+        return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
     }
 
-    private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) throws IOException {
+
+    private static NetconfMessage sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfClient netconfClient) throws IOException {
         try {
-            return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
-        } catch (RuntimeException e) {
+            NetconfMessage netconfMessage = netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
+            NetconfUtil.checkIsMessageOk(netconfMessage);
+            return netconfMessage;
+        } catch (RuntimeException e) { // TODO: change NetconfClient#sendMessage to throw checked exceptions
             logger.debug("Error while executing netconf transaction {} to {}", request, netconfClient, e);
             throw new IOException("Failed to execute netconf transaction", e);
         }
     }
 
-    private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) throws IOException, SAXException {
-        try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
-            Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
+
+    // load editConfig.xml template, populate /rpc/edit-config/config with parameter
+    private static NetconfMessage createEditConfigMessage(Element dataElement) {
+        String editConfigResourcePath = "/netconfOp/editConfig.xml";
+        try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
+            Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
 
             Document doc = XmlUtil.readXmlToDocument(stream);
 
-            doc.getDocumentElement();
             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
-                configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
+                boolean deep = true;
+                configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
             }
             editConfigElement.appendChild(configWrapper.getDomElement());
             return new NetconfMessage(doc);
         } catch (IOException | SAXException e) {
-            logger.debug("Failed to create edit-config message for resource {}", editConfigResourcename, e);
-            throw e;
+            // error reading the xml file bundled into the jar
+            throw new RuntimeException("Error while opening local resource " + editConfigResourcePath, e);
         }
     }
 
-    private static NetconfMessage getNetconfMessageFromResource(String resource) throws IOException, SAXException {
+    private static NetconfMessage getCommitMessage() {
+        String resource = "/netconfOp/commit.xml";
         try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
             Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
         } catch (SAXException | IOException e) {
-            logger.debug("Failed to parse netconf message for resource {}", resource, e);
-            throw e;
+            // error reading the xml file bundled into the jar
+            throw new RuntimeException("Error while opening local resource " + resource, e);
+        }
+    }
+
+    static class EditAndCommitResponse {
+        private final NetconfMessage editResponse, commitResponse;
+
+        EditAndCommitResponse(NetconfMessage editResponse, NetconfMessage commitResponse) {
+            this.editResponse = editResponse;
+            this.commitResponse = commitResponse;
+        }
+
+        public NetconfMessage getEditResponse() {
+            return editResponse;
+        }
+
+        public NetconfMessage getCommitResponse() {
+            return commitResponse;
+        }
+
+        @Override
+        public String toString() {
+            return "EditAndCommitResponse{" +
+                    "editResponse=" + editResponse +
+                    ", commitResponse=" + commitResponse +
+                    '}';
+        }
+    }
+
+
+    static class EditAndCommitResponseWithRetries {
+        private final EditAndCommitResponse editAndCommitResponse;
+        private final int retries;
+
+        EditAndCommitResponseWithRetries(EditAndCommitResponse editAndCommitResponse, int retries) {
+            this.editAndCommitResponse = editAndCommitResponse;
+            this.retries = retries;
+        }
+
+        public int getRetries() {
+            return retries;
+        }
+
+        public EditAndCommitResponse getEditAndCommitResponse() {
+            return editAndCommitResponse;
+        }
+
+        @Override
+        public String toString() {
+            return "EditAndCommitResponseWithRetries{" +
+                    "editAndCommitResponse=" + editAndCommitResponse +
+                    ", retries=" + retries +
+                    '}';
         }
     }
-}
+}
\ No newline at end of file
index 179c9681fc4b21732286442251f5029e19e6958c..1157ddbd83a814be6d7ea4091ea116bf8398255d 100644 (file)
@@ -10,11 +10,9 @@ package org.opendaylight.controller.netconf.persist.impl.osgi;
 
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
-import org.opendaylight.controller.netconf.client.NetconfClient;
 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
 import org.opendaylight.controller.netconf.persist.impl.ConfigPusher;
 import org.opendaylight.controller.netconf.persist.impl.PersisterAggregator;
-import org.opendaylight.controller.netconf.persist.impl.Util;
 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
@@ -25,7 +23,6 @@ import javax.management.MBeanServer;
 import java.lang.management.ManagementFactory;
 import java.net.InetSocketAddress;
 import java.util.regex.Pattern;
-import java.util.concurrent.TimeUnit;
 
 public class ConfigPersisterActivator implements BundleActivator {
 
@@ -34,7 +31,7 @@ public class ConfigPersisterActivator implements BundleActivator {
     private final static MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
     private static final String IGNORED_MISSING_CAPABILITY_REGEX_SUFFIX = "ignoredMissingCapabilityRegex";
 
-    private static final String PUSH_TIMEOUT = "pushTimeout";
+    private static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS = "maxWaitForCapabilitiesMillis";
 
     public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister";
 
@@ -44,9 +41,8 @@ public class ConfigPersisterActivator implements BundleActivator {
 
 
     private volatile ConfigPersisterNotificationHandler jmxNotificationHandler;
-    private volatile NetconfClient netconfClient;
     private Thread initializationThread;
-    private EventLoopGroup nettyThreadgroup;
+    private EventLoopGroup nettyThreadGroup;
     private PersisterAggregator persisterAggregator;
 
     @Override
@@ -63,15 +59,22 @@ public class ConfigPersisterActivator implements BundleActivator {
             regex = DEFAULT_IGNORED_REGEX;
         }
 
-        String timeoutProperty = propertiesProvider.getProperty(PUSH_TIMEOUT);
-        long timeout = timeoutProperty == null ? ConfigPusher.DEFAULT_TIMEOUT : TimeUnit.SECONDS.toNanos(Integer.valueOf(timeoutProperty));
+        String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS);
+        long maxWaitForCapabilitiesMillis;
+        if (timeoutProperty == null) {
+            maxWaitForCapabilitiesMillis = ConfigPusher.DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS;
+        } else {
+            maxWaitForCapabilitiesMillis = Integer.valueOf(timeoutProperty);
+        }
 
         final Pattern ignoredMissingCapabilityRegex = Pattern.compile(regex);
-        nettyThreadgroup = new NioEventLoopGroup();
+        nettyThreadGroup = new NioEventLoopGroup();
 
         persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider);
-        final InetSocketAddress address = NetconfConfigUtil.extractTCPNetconfAddress(context, "Netconf is not configured, persister is not operational", true);
-        final ConfigPusher configPusher = new ConfigPusher(address, nettyThreadgroup);
+        final InetSocketAddress address = NetconfConfigUtil.extractTCPNetconfAddress(context,
+                "Netconf is not configured, persister is not operational", true);
+        final ConfigPusher configPusher = new ConfigPusher(address, nettyThreadGroup, maxWaitForCapabilitiesMillis,
+                ConfigPusher.DEFAULT_CONNECTION_TIMEOUT_MILLIS);
 
 
         // offload initialization to another thread in order to stop blocking activator
@@ -79,11 +82,9 @@ public class ConfigPersisterActivator implements BundleActivator {
             @Override
             public void run() {
                 try {
-                    netconfClient = configPusher.init(persisterAggregator.loadLastConfigs());
-                    jmxNotificationHandler = new ConfigPersisterNotificationHandler(
-                            platformMBeanServer, netconfClient, persisterAggregator,
+                    configPusher.pushConfigs(persisterAggregator.loadLastConfigs());
+                    jmxNotificationHandler = new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator,
                             ignoredMissingCapabilityRegex);
-                    jmxNotificationHandler.init();
                 } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     logger.error("Interrupted while waiting for netconf connection");
@@ -103,15 +104,7 @@ public class ConfigPersisterActivator implements BundleActivator {
         if (jmxNotificationHandler != null) {
             jmxNotificationHandler.close();
         }
-        if (netconfClient != null) {
-            netconfClient = jmxNotificationHandler.getNetconfClient();
-            try {
-                Util.closeClientAndDispatcher(netconfClient);
-            } catch (Exception e) {
-                logger.warn("Unable to close connection to netconf {}", netconfClient, e);
-            }
-        }
-        nettyThreadgroup.shutdownGracefully();
+        nettyThreadGroup.shutdownGracefully();
         persisterAggregator.close();
     }
 }
index 67d95bb90f74ac2098c4677e5cdab002cb1624da..4fcad2cbd6afef217f32d23f71383f13f277414c 100644 (file)
@@ -8,16 +8,11 @@
 
 package org.opendaylight.controller.netconf.client;
 
+import com.google.common.base.Preconditions;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Sets;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GlobalEventExecutor;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.Set;
-import java.util.concurrent.CancellationException;
-import java.util.concurrent.ExecutionException;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
 import org.opendaylight.protocol.framework.ReconnectStrategy;
@@ -25,8 +20,13 @@ import org.opendaylight.protocol.framework.TimedReconnectStrategy;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Set;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 
 public class NetconfClient implements Closeable {
 
@@ -103,7 +103,7 @@ public class NetconfClient implements Closeable {
     }
 
     public NetconfMessage sendMessage(NetconfMessage message, int attempts, int attemptMsDelay) {
-        long startTime = System.currentTimeMillis();
+        Stopwatch stopwatch = new Stopwatch().start();
         Preconditions.checkState(clientSession.isUp(), "Session was not up yet");
         //logger.debug("Sending message: {}",XmlUtil.toString(message.getDocument()));
         clientSession.sendMessage(message);
@@ -115,8 +115,8 @@ public class NetconfClient implements Closeable {
         } catch (IllegalStateException e) {
             throw new IllegalStateException(this + " Cannot read message from " + address, e);
         } finally {
-            long diffMillis = System.currentTimeMillis() - startTime;
-            logger.debug("Total time spent waiting for response {}", diffMillis);
+            stopwatch.stop();
+            logger.debug("Total time spent waiting for response {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
         }
     }
 
index fc6f87db5d797748d622364b8db3dd5e9a65f58e..1228a84a8a71a07fb1be4438407c5c8e8e4af54f 100644 (file)
@@ -8,15 +8,12 @@
 
 package org.opendaylight.controller.netconf.client;
 
+import com.google.common.base.Optional;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.Promise;
-
-import java.io.Closeable;
-import java.net.InetSocketAddress;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfSession;
 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
@@ -28,7 +25,8 @@ import org.opendaylight.protocol.framework.SessionListenerFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
+import java.io.Closeable;
+import java.net.InetSocketAddress;
 
 public class NetconfClientDispatcher extends AbstractDispatcher<NetconfClientSession, NetconfClientSessionListener> implements Closeable {
 
@@ -37,16 +35,16 @@ public class NetconfClientDispatcher extends AbstractDispatcher<NetconfClientSes
     private final NetconfClientSessionNegotiatorFactory negotatorFactory;
     private final HashedWheelTimer timer;
 
-    public NetconfClientDispatcher(EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
+    public NetconfClientDispatcher(EventLoopGroup bossGroup, EventLoopGroup workerGroup, long clientConnectionTimeoutMillis) {
         super(bossGroup, workerGroup);
         timer = new HashedWheelTimer();
-        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.<String>absent());
+        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.<String>absent(), clientConnectionTimeoutMillis);
     }
 
-    public NetconfClientDispatcher(EventLoopGroup bossGroup, EventLoopGroup workerGroup, String additionalHeader) {
+    public NetconfClientDispatcher(EventLoopGroup bossGroup, EventLoopGroup workerGroup, String additionalHeader, long connectionTimeoutMillis) {
         super(bossGroup, workerGroup);
         timer = new HashedWheelTimer();
-        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.of(additionalHeader));
+        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.of(additionalHeader), connectionTimeoutMillis);
     }
 
     public Future<NetconfClientSession> createClient(InetSocketAddress address,
index dd8e3c9664588bf5350ad48ec1c1bfdc2b480b60..100b98c15af18e1791dc4c43fcc460189ee4384e 100644 (file)
@@ -34,8 +34,9 @@ public class NetconfClientSessionNegotiator extends
         AbstractNetconfSessionNegotiator<NetconfSessionPreferences, NetconfClientSession> {
 
     protected NetconfClientSessionNegotiator(NetconfSessionPreferences sessionPreferences,
-            Promise<NetconfClientSession> promise, Channel channel, Timer timer, SessionListener sessionListener) {
-        super(sessionPreferences, promise, channel, timer, sessionListener);
+            Promise<NetconfClientSession> promise, Channel channel, Timer timer, SessionListener sessionListener,
+            long connectionTimeoutMillis) {
+        super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
     }
 
     private static Collection<String> getCapabilities(Document doc) {
index abfbdd526c5f7bb6796c7c0273060e7b91aa8933..db6c024e5afe24e35d336ce2c5322340814289eb 100644 (file)
@@ -8,13 +8,11 @@
 
 package org.opendaylight.controller.netconf.client;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import io.netty.channel.Channel;
 import io.netty.util.Timer;
 import io.netty.util.concurrent.Promise;
-
-import java.io.IOException;
-import java.io.InputStream;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
@@ -23,18 +21,20 @@ import org.opendaylight.protocol.framework.SessionNegotiator;
 import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
 import org.xml.sax.SAXException;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.io.InputStream;
 
 public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory {
 
     private final Timer timer;
 
     private final Optional<String> additionalHeader;
+    private final long connectionTimeoutMillis;
 
-    public NetconfClientSessionNegotiatorFactory(Timer timer, Optional<String> additionalHeader) {
+    public NetconfClientSessionNegotiatorFactory(Timer timer, Optional<String> additionalHeader, long connectionTimeoutMillis) {
         this.timer = timer;
         this.additionalHeader = additionalHeader;
+        this.connectionTimeoutMillis = connectionTimeoutMillis;
     }
 
     private static NetconfMessage loadHelloMessageTemplate() {
@@ -57,7 +57,7 @@ public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorF
         }
         NetconfSessionPreferences proposal = new NetconfSessionPreferences(helloMessage);
         return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
-                sessionListenerFactory.getSessionListener());
+                sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
     }
 
 }
index ee07b3949d6dd2f040da183a46dde263abe6d9af..06239b2bfd4ef000345229c6c12c5791429751d0 100644 (file)
@@ -8,16 +8,13 @@
 
 package org.opendaylight.controller.netconf.client;
 
+import com.google.common.base.Optional;
 import io.netty.channel.ChannelHandler;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.Promise;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfSession;
 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
@@ -33,7 +30,8 @@ import org.opendaylight.protocol.framework.ReconnectStrategy;
 import org.opendaylight.protocol.framework.SessionListener;
 import org.opendaylight.protocol.framework.SessionListenerFactory;
 
-import com.google.common.base.Optional;
+import java.io.IOException;
+import java.net.InetSocketAddress;
 
 public class NetconfSshClientDispatcher extends NetconfClientDispatcher {
 
@@ -42,19 +40,19 @@ public class NetconfSshClientDispatcher extends NetconfClientDispatcher {
     private NetconfClientSessionNegotiatorFactory negotatorFactory;
 
     public NetconfSshClientDispatcher(AuthenticationHandler authHandler, EventLoopGroup bossGroup,
-            EventLoopGroup workerGroup) {
-        super(bossGroup, workerGroup);
+            EventLoopGroup workerGroup, long connectionTimeoutMillis) {
+        super(bossGroup, workerGroup, connectionTimeoutMillis);
         this.authHandler = authHandler;
         this.timer = new HashedWheelTimer();
-        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.<String>absent());
+        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.<String>absent(), connectionTimeoutMillis);
     }
 
     public NetconfSshClientDispatcher(AuthenticationHandler authHandler, EventLoopGroup bossGroup,
-            EventLoopGroup workerGroup, String additionalHeader) {
-        super(bossGroup, workerGroup, additionalHeader);
+            EventLoopGroup workerGroup, String additionalHeader, long socketTimeoutMillis) {
+        super(bossGroup, workerGroup, additionalHeader, socketTimeoutMillis);
         this.authHandler = authHandler;
         this.timer = new HashedWheelTimer();
-        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.of(additionalHeader));
+        this.negotatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.of(additionalHeader), socketTimeoutMillis);
     }
 
     public Future<NetconfClientSession> createClient(InetSocketAddress address,
index 7f1d289c5be88fbec6c30b444fd282617efec158..a3cc10417e389123169abe940d05cddf7f98b85b 100644 (file)
@@ -29,7 +29,7 @@ public class SSHNetconfClientLiveTest {
         nettyThreadgroup = new NioEventLoopGroup();
         netconfClientDispatcher = new NetconfSshClientDispatcher(new LoginPassword(
                 System.getProperty("username"), System.getProperty("password")),
-                nettyThreadgroup, nettyThreadgroup);
+                nettyThreadgroup, nettyThreadgroup, 5000);
     }
 
     @Test
index 8ba4cdc052057333df0154162153adf9ee663e2f..91555861dc4aaaa51fdfd69dd24ae9bb834f02e7 100644 (file)
@@ -8,12 +8,10 @@
 
 package org.opendaylight.controller.netconf.impl;
 
+import com.google.common.base.Optional;
 import io.netty.channel.Channel;
 import io.netty.util.Timer;
 import io.netty.util.concurrent.Promise;
-
-import java.net.InetSocketAddress;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
 import org.opendaylight.controller.netconf.impl.util.AdditionalHeaderUtil;
@@ -22,7 +20,7 @@ import org.opendaylight.protocol.framework.SessionListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
+import java.net.InetSocketAddress;
 
 public class NetconfServerSessionNegotiator extends
         AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession> {
@@ -30,8 +28,9 @@ public class NetconfServerSessionNegotiator extends
     static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
 
     protected NetconfServerSessionNegotiator(NetconfServerSessionPreferences sessionPreferences,
-            Promise<NetconfServerSession> promise, Channel channel, Timer timer, SessionListener sessionListener) {
-        super(sessionPreferences, promise, channel, timer, sessionListener);
+            Promise<NetconfServerSession> promise, Channel channel, Timer timer, SessionListener sessionListener,
+            long connectionTimeoutMillis) {
+        super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
     }
 
     @Override
index 3c14d5124f395f54182ce125e1a9bed4ccf03d93..98462b8025ce965b596cfd323484164eaa7c97d1 100644 (file)
@@ -40,12 +40,14 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
     private static final Document helloMessageTemplate = loadHelloMessageTemplate();
     private final SessionIdProvider idProvider;
     private final NetconfOperationServiceFactoryListener factoriesListener;
+    private final long connectionTimeoutMillis;
 
     public NetconfServerSessionNegotiatorFactory(Timer timer, NetconfOperationServiceFactoryListener factoriesListener,
-            SessionIdProvider idProvider) {
+            SessionIdProvider idProvider, long connectionTimeoutMillis) {
         this.timer = timer;
         this.factoriesListener = factoriesListener;
         this.idProvider = idProvider;
+        this.connectionTimeoutMillis = connectionTimeoutMillis;
     }
 
     private static Document loadHelloMessageTemplate() {
@@ -64,7 +66,7 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
         NetconfServerSessionPreferences proposal = new NetconfServerSessionPreferences(createHelloMessage(sessionId),
                 sessionId);
         return new NetconfServerSessionNegotiator(proposal, promise, channel, timer,
-                sessionListenerFactory.getSessionListener());
+                sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
     }
 
     private static final XPathExpression sessionIdXPath = XMLNetconfUtil
index abebacf974d0527b72d6479fb2e83796e18aedd4..95f7353600fcfb67a5626a496d76642613c4bb5a 100644 (file)
@@ -48,8 +48,9 @@ public class NetconfImplActivator implements BundleActivator {
 
         SessionIdProvider idProvider = new SessionIdProvider();
         timer = new HashedWheelTimer();
+        long connectionTimeoutMillis = NetconfConfigUtil.extractTimeoutMillis(context);
         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                timer, factoriesListener, idProvider);
+                timer, factoriesListener, idProvider, connectionTimeoutMillis);
 
         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
index 958ac4239842c535b9597f21270883d5c5b8b864..0ef2c285e407ac65b9eb62e0bbfc2d14b555c242 100644 (file)
@@ -8,34 +8,14 @@
 
 package org.opendaylight.controller.netconf.impl;
 
-import static com.google.common.base.Preconditions.checkNotNull;
-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.Optional;
+import com.google.common.collect.Sets;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.util.HashedWheelTimer;
-
-import java.io.DataOutputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.management.ManagementFactory;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.ObjectName;
-
 import org.apache.commons.io.IOUtils;
 import org.junit.After;
-import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
@@ -63,15 +43,30 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
+import javax.management.ObjectName;
+import java.io.DataOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.management.ManagementFactory;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+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;
 
 public class ConcurrentClientsTest {
 
     private static final int CONCURRENCY = 16;
-    private static EventLoopGroup nettyGroup = new NioEventLoopGroup();
-    public static final NetconfClientDispatcher NETCONF_CLIENT_DISPATCHER =
-            new NetconfClientDispatcher( nettyGroup, nettyGroup);
+    private EventLoopGroup nettyGroup;
+    private NetconfClientDispatcher netconfClientDispatcher;
 
     @Mock
     private YangStoreService yangStoreService;
@@ -88,6 +83,8 @@ public class ConcurrentClientsTest {
     @Mock
     private SessionMonitoringService monitoring;
 
+    HashedWheelTimer hashedWheelTimer;
+
     @Before
     public void setUp() throws Exception {
         { // init mocks
@@ -102,12 +99,16 @@ public class ConcurrentClientsTest {
             doReturn(Collections.emptySet()).when(jmxClient).lookupConfigBeans();
         }
 
+        nettyGroup = new NioEventLoopGroup();
+        netconfClientDispatcher = new NetconfClientDispatcher( nettyGroup, nettyGroup, 5000);
+
         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
         factoriesListener.onAddNetconfOperationServiceFactory(mockOpF());
 
         SessionIdProvider idProvider = new SessionIdProvider();
+        hashedWheelTimer = new HashedWheelTimer();
         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
+                hashedWheelTimer, factoriesListener, idProvider, 5000);
 
         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
@@ -123,8 +124,9 @@ public class ConcurrentClientsTest {
         s.await();
     }
 
-    @AfterClass
-    public static void tearDownStatic() {
+    @After
+    public void tearDown(){
+        hashedWheelTimer.stop();
         nettyGroup.shutdownGracefully();
     }
 
@@ -285,7 +287,7 @@ public class ConcurrentClientsTest {
         @Override
         public void run() {
             try {
-                final NetconfClient netconfClient = new NetconfClient(clientId, netconfAddress, NETCONF_CLIENT_DISPATCHER);
+                final NetconfClient netconfClient = new NetconfClient(clientId, netconfAddress, netconfClientDispatcher);
                 long sessionId = netconfClient.getSessionId();
                 logger.info("Client with sessionid {} hello exchanged", sessionId);
 
index 0ecc1cb38324ede5b3443706a071a68a3d21a9dc..9835c2393ba489e7dcf7ead4ceca119beef7f63b 100644 (file)
@@ -26,6 +26,7 @@ public class NetconfDispatcherImplTest {
     private EventLoopGroup nettyGroup;
     private NetconfServerDispatcher dispatch;
     private DefaultCommitNotificationProducer commitNot;
+    private HashedWheelTimer hashedWheelTimer;
 
     @Before
     public void setUp() throws Exception {
@@ -36,8 +37,9 @@ public class NetconfDispatcherImplTest {
         NetconfOperationServiceFactoryListener factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
 
         SessionIdProvider idProvider = new SessionIdProvider();
+        hashedWheelTimer = new HashedWheelTimer();
         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(), factoriesListener, idProvider);
+                hashedWheelTimer, factoriesListener, idProvider, 5000);
 
         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
                 factoriesListener, commitNot, idProvider, null);
@@ -49,6 +51,7 @@ public class NetconfDispatcherImplTest {
 
     @After
     public void tearDown() throws Exception {
+        hashedWheelTimer.stop();
         commitNot.close();
         nettyGroup.shutdownGracefully();
     }
diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java
new file mode 100644 (file)
index 0000000..b261218
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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.it;
+
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.util.HashedWheelTimer;
+import org.junit.After;
+import org.junit.Before;
+import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
+import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
+import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
+import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
+import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
+import org.opendaylight.controller.netconf.impl.SessionIdProvider;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
+import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
+
+public class AbstractNetconfConfigTest extends AbstractConfigTest {
+
+    protected EventLoopGroup nettyThreadgroup;
+    private HashedWheelTimer hashedWheelTimer;
+
+    @Before
+    public void setUpAbstractNetconfConfigTest() {
+        nettyThreadgroup = new NioEventLoopGroup();
+        hashedWheelTimer = new HashedWheelTimer();
+    }
+
+
+    protected NetconfServerDispatcher createDispatcher(
+            NetconfOperationServiceFactoryListenerImpl factoriesListener, SessionMonitoringService sessionMonitoringService,
+            DefaultCommitNotificationProducer commitNotifier) {
+        SessionIdProvider idProvider = new SessionIdProvider();
+
+        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
+                hashedWheelTimer, factoriesListener, idProvider, 5000);
+
+        NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
+                factoriesListener, commitNotifier, idProvider,
+                sessionMonitoringService);
+
+        NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
+                serverNegotiatorFactory, listenerFactory);
+        return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+    }
+
+
+    @After
+    public void cleanUpTimer() {
+        hashedWheelTimer.stop();
+        nettyThreadgroup.shutdownGracefully();
+    }
+
+}
index 14f70d398c6874f5922488fbb802540d5d97bc95..0037981a3e0103f95cd83a945af5aa83c11dd477 100644 (file)
@@ -10,17 +10,14 @@ package org.opendaylight.controller.netconf.it;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import io.netty.channel.ChannelFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
 import org.apache.commons.lang3.StringUtils;
+import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.matchers.JUnitMatchers;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.api.Persister;
@@ -35,9 +32,6 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
-import org.opendaylight.controller.netconf.impl.SessionIdProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
@@ -63,7 +57,6 @@ import java.net.InetSocketAddress;
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
 import java.util.regex.Pattern;
 
 import static junit.framework.Assert.assertEquals;
@@ -74,16 +67,18 @@ import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
-public class NetconfConfigPersisterITTest extends AbstractConfigTest {
+public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
 
     private static final Logger logger =  LoggerFactory.getLogger(NetconfConfigPersisterITTest.class);
 
     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
 
-    private EventLoopGroup nettyThreadgroup;
+
 
     private NetconfClientDispatcher clientDispatcher;
 
+    DefaultCommitNotificationProducer commitNotifier;
+
     @Before
     public void setUp() throws Exception {
         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(NetconfITTest.getModuleFactoriesS().toArray(
@@ -97,13 +92,18 @@ public class NetconfConfigPersisterITTest extends AbstractConfigTest {
                 .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
                         new NetconfMonitoringOperationService(monitoringService)));
 
-        nettyThreadgroup = new NioEventLoopGroup();
 
-        NetconfServerDispatcher dispatch = createDispatcher(factoriesListener);
+        commitNotifier = new DefaultCommitNotificationProducer(platformMBeanServer);
+        NetconfServerDispatcher dispatch = createDispatcher(factoriesListener, mockSessionMonitoringService(), commitNotifier);
         ChannelFuture s = dispatch.createServer(tcpAddress);
         s.await();
 
-        clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup);
+        clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
+    }
+
+    @After
+    public void cleanUp(){
+        commitNotifier.close();
     }
 
     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
@@ -111,27 +111,16 @@ public class NetconfConfigPersisterITTest extends AbstractConfigTest {
         return new HardcodedYangStoreService(yangDependencies);
     }
 
-    private NetconfServerDispatcher createDispatcher(
-                                                     NetconfOperationServiceFactoryListenerImpl factoriesListener) {
-        SessionIdProvider idProvider = new SessionIdProvider();
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
-
-        NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
-                factoriesListener, new DefaultCommitNotificationProducer(platformMBeanServer), idProvider, mockSessionMonitoringService());
-
-        NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
-                serverNegotiatorFactory, listenerFactory);
-        return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
-    }
 
-    private SessionMonitoringService mockSessionMonitoringService() {
+    protected SessionMonitoringService mockSessionMonitoringService() {
         SessionMonitoringService mockedSessionMonitor = mock(SessionMonitoringService.class);
         doNothing().when(mockedSessionMonitor).onSessionUp(any(NetconfManagementSession.class));
         doNothing().when(mockedSessionMonitor).onSessionDown(any(NetconfManagementSession.class));
         return mockedSessionMonitor;
     }
 
+
+
     @Test
     public void testNetconfCommitNotifications() throws Exception {
 
@@ -139,22 +128,22 @@ public class NetconfConfigPersisterITTest extends AbstractConfigTest {
         VerifyingPersister mockedAggregator = mockAggregator();
 
         try (NetconfClient persisterClient = new NetconfClient("persister", tcpAddress, 4000, clientDispatcher)) {
-            ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler(
-                    platformMBeanServer, persisterClient, mockedAggregator,
-                    Pattern.compile(""));
-            configPersisterNotificationHandler.init();
-
-            try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
-                NetconfMessage response = netconfClient.sendMessage(loadGetConfigMessage());
-                assertResponse(response, "<modules");
-                assertResponse(response, "<services");
-                response = netconfClient.sendMessage(loadCommitMessage());
-                assertResponse(response, "ok");
-
-                response = netconfClient.sendMessage(loadEditConfigMessage());
-                assertResponse(response, "ok");
-                response = netconfClient.sendMessage(loadCommitMessage());
-                assertResponse(response, "ok");
+            try (ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler(
+                    platformMBeanServer, mockedAggregator, Pattern.compile(""))) {
+
+
+                try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
+                    NetconfMessage response = netconfClient.sendMessage(loadGetConfigMessage());
+                    assertResponse(response, "<modules");
+                    assertResponse(response, "<services");
+                    response = netconfClient.sendMessage(loadCommitMessage());
+                    assertResponse(response, "ok");
+
+                    response = netconfClient.sendMessage(loadEditConfigMessage());
+                    assertResponse(response, "ok");
+                    response = netconfClient.sendMessage(loadCommitMessage());
+                    assertResponse(response, "ok");
+                }
             }
         }
 
index 793a756d540ecf7fee82499121db0bdb6b0f167f..44775fdf9316fdc582b5df3a3f5313f9b0b94b55 100644 (file)
@@ -9,27 +9,9 @@
 package org.opendaylight.controller.netconf.it;
 
 import io.netty.channel.ChannelFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.management.ManagementFactory;
-import java.net.InetSocketAddress;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
@@ -39,18 +21,28 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
-import org.opendaylight.controller.netconf.impl.SessionIdProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
 
-public class NetconfITSecureTest extends AbstractConfigTest {
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.management.ManagementFactory;
+import java.net.InetSocketAddress;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.util.Collection;
+import java.util.List;
+
+public class NetconfITSecureTest extends AbstractNetconfConfigTest {
 
     private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
 
     private DefaultCommitNotificationProducer commitNot;
     private NetconfServerDispatcher dispatchS;
-    private EventLoopGroup nettyThreadgroup;
 
 
     @Before
@@ -63,7 +55,6 @@ public class NetconfITSecureTest extends AbstractConfigTest {
 
         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
-        nettyThreadgroup = new NioEventLoopGroup();
 
         dispatchS = createDispatcher(factoriesListener);
         ChannelFuture s = dispatchS.createServer(tlsAddress);
@@ -71,22 +62,12 @@ public class NetconfITSecureTest extends AbstractConfigTest {
     }
 
     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
-        SessionIdProvider idProvider = new SessionIdProvider();
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
-
-        NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
-                factoriesListener, commitNot, idProvider, NetconfITTest.getNetconfMonitoringListenerService());
-
-        NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
-                serverNegotiatorFactory, listenerFactory);
-        return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+        return super.createDispatcher(factoriesListener, NetconfITTest.getNetconfMonitoringListenerService(), commitNot);
     }
 
     @After
     public void tearDown() throws Exception {
         commitNot.close();
-        nettyThreadgroup.shutdownGracefully();
     }
 
     private SSLContext getSslContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
@@ -110,7 +91,7 @@ public class NetconfITSecureTest extends AbstractConfigTest {
 
     @Test
     public void testSecure() throws Exception {
-        NetconfClientDispatcher dispatch = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup);
+        NetconfClientDispatcher dispatch = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
         try (NetconfClient netconfClient = new NetconfClient("tls-client", tlsAddress, 4000, dispatch))  {
 
         }
index 5f4bcecff05ed6e75e8725082a618ce517ffad16..954da5f4874a03c10f772822a163750d451f0e6b 100644 (file)
@@ -13,15 +13,11 @@ import ch.ethz.ssh2.Session;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import io.netty.channel.ChannelFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
 import junit.framework.Assert;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
@@ -38,9 +34,6 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
-import org.opendaylight.controller.netconf.impl.SessionIdProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
@@ -71,7 +64,6 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
 
 import static java.util.Collections.emptyList;
 import static junit.framework.Assert.assertEquals;
@@ -81,7 +73,7 @@ import static org.mockito.Matchers.anyLong;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
-public class NetconfITTest extends AbstractConfigTest {
+public class NetconfITTest extends AbstractNetconfConfigTest {
 
     // TODO refactor, pull common code up to AbstractNetconfITTest
 
@@ -96,7 +88,6 @@ public class NetconfITTest extends AbstractConfigTest {
             closeSession, startExi, stopExi;
     private DefaultCommitNotificationProducer commitNot;
     private NetconfServerDispatcher dispatch;
-    private EventLoopGroup nettyThreadgroup;
 
     private NetconfClientDispatcher clientDispatcher;
 
@@ -110,7 +101,6 @@ public class NetconfITTest extends AbstractConfigTest {
         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
 
-        nettyThreadgroup = new NioEventLoopGroup();
 
         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
@@ -118,20 +108,11 @@ public class NetconfITTest extends AbstractConfigTest {
         ChannelFuture s = dispatch.createServer(tcpAddress);
         s.await();
 
-        clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup);
+        clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup, 5000);
     }
 
     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
-        SessionIdProvider idProvider = new SessionIdProvider();
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
-
-        NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
-                factoriesListener, commitNot, idProvider, getNetconfMonitoringListenerService());
-
-        NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
-                serverNegotiatorFactory, listenerFactory);
-        return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+        return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
     }
 
     static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
@@ -145,7 +126,6 @@ public class NetconfITTest extends AbstractConfigTest {
     @After
     public void tearDown() throws Exception {
         commitNot.close();
-        nettyThreadgroup.shutdownGracefully();
         clientDispatcher.close();
     }
 
index b0821799b0b57ad94682fe6ec58cba61ac0dee97..be2c32e34fd8816b28ed1a844437b5d0c133ea56 100644 (file)
@@ -11,15 +11,11 @@ import com.google.common.base.Charsets;
 import com.google.common.base.Optional;
 import com.google.common.collect.Sets;
 import io.netty.channel.ChannelFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
 import junit.framework.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.matchers.JUnitMatchers;
 import org.mockito.Mock;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
@@ -31,9 +27,6 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
-import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
-import org.opendaylight.controller.netconf.impl.SessionIdProvider;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
@@ -57,13 +50,12 @@ import java.net.Socket;
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
 
 import static org.mockito.Matchers.anyLong;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
-public class NetconfMonitoringITTest extends AbstractConfigTest {
+public class NetconfMonitoringITTest extends AbstractNetconfConfigTest {
 
     private static final Logger logger =  LoggerFactory.getLogger(NetconfITTest.class);
 
@@ -72,7 +64,6 @@ public class NetconfMonitoringITTest extends AbstractConfigTest {
     @Mock
     private DefaultCommitNotificationProducer commitNot;
     private NetconfServerDispatcher dispatch;
-    private EventLoopGroup nettyThreadgroup;
 
     private NetconfClientDispatcher clientDispatcher;
 
@@ -91,13 +82,12 @@ public class NetconfMonitoringITTest extends AbstractConfigTest {
                 .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
                         new NetconfMonitoringOperationService(monitoringService)));
 
-        nettyThreadgroup = new NioEventLoopGroup();
 
         dispatch = createDispatcher(factoriesListener);
         ChannelFuture s = dispatch.createServer(tcpAddress);
         s.await();
 
-        clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup);
+        clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
     }
 
     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
@@ -107,16 +97,7 @@ public class NetconfMonitoringITTest extends AbstractConfigTest {
 
     private NetconfServerDispatcher createDispatcher(
                                                      NetconfOperationServiceFactoryListenerImpl factoriesListener) {
-        SessionIdProvider idProvider = new SessionIdProvider();
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
-                new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
-
-        NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
-                factoriesListener, commitNot, idProvider, getNetconfMonitoringListenerService(logger, monitoringService));
-
-        NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
-                serverNegotiatorFactory, listenerFactory);
-        return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+        return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(logger, monitoringService), commitNot);
     }
 
     static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) {
index 26ea7ceb79d4b78d98ecf42af34d7be87364ffcb..8cfd177fceff03dad3cd1609d11152f30e55811a 100644 (file)
@@ -42,9 +42,6 @@ import java.util.concurrent.TimeUnit;
 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends NetconfSession>
         extends AbstractSessionNegotiator<NetconfMessage, S> {
 
-    // TODO Adjust wait time for negotiation, now is 1 minute ?
-    private static final long INITIAL_HOLDTIMER = 1;
-
     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
 
@@ -62,13 +59,15 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
 
     private State state = State.IDLE;
     private final Timer timer;
+    private final long connectionTimeoutMillis;
 
     protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
-            SessionListener sessionListener) {
+            SessionListener sessionListener, long connectionTimeoutMillis) {
         super(promise, channel);
         this.sessionPreferences = sessionPreferences;
         this.timer = timer;
         this.sessionListener = sessionListener;
+        this.connectionTimeoutMillis = connectionTimeoutMillis;
     }
 
     @Override
@@ -120,6 +119,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
             public void run(final Timeout timeout) throws Exception {
                 synchronized (this) {
                     if (state != State.ESTABLISHED) {
+                        logger.debug("Connection timeout after {}", timeout);
                         final IllegalStateException cause = new IllegalStateException(
                                 "Session was not established after " + timeout);
                         negotiationFailed(cause);
@@ -129,7 +129,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
                     }
                 }
             }
-        }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
+        }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
 
         sendMessage(helloMessage);
         changeState(State.OPEN_WAIT);
index b67f48f5fcf3014b06f701c18a956bfed0a78e5b..a2486050f9368e7ff37314a1e65e38e7134406ed 100644 (file)
@@ -8,17 +8,17 @@
 
 package org.opendaylight.controller.netconf.util.handler;
 
+import com.google.common.base.Charsets;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.ByteToMessageDecoder;
-
-import java.util.List;
-
 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.List;
+
 public class NetconfMessageAggregator extends ByteToMessageDecoder {
 
     private final static Logger logger = LoggerFactory.getLogger(NetconfMessageAggregator.class);
@@ -36,6 +36,10 @@ public class NetconfMessageAggregator extends ByteToMessageDecoder {
         int index = indexOfSequence(in, eom);
         if (index == -1) {
             logger.debug("Message is not complete, read again.");
+            if (logger.isTraceEnabled()) {
+                String str = in.toString(Charsets.UTF_8);
+                logger.trace("Message read so far: {}", str);
+            }
             ctx.read();
         } else {
             ByteBuf msg = in.readBytes(index);
index 55ed7e074423968dd7e7626e45a181893cdfd4a1..38563cba93eef1f727330b17ff72879a012f70ff 100644 (file)
@@ -8,14 +8,22 @@
 
 package org.opendaylight.controller.netconf.util.osgi;
 
-        import com.google.common.base.Optional;
-        import java.net.InetSocketAddress;
-        import org.osgi.framework.BundleContext;
-        import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.base.Optional;
+import org.osgi.framework.BundleContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.InetSocketAddress;
+
+import static com.google.common.base.Preconditions.checkNotNull;
 
 public class NetconfConfigUtil {
+    private static final Logger logger = LoggerFactory.getLogger(NetconfConfigUtil.class);
+
     private static final String PREFIX_PROP = "netconf.";
 
+
+
     private enum InfixProp {
         tcp, ssh
     }
@@ -25,6 +33,23 @@ public class NetconfConfigUtil {
     private static final String CLIENT_PROP = ".client";
     private static final String PRIVATE_KEY_PATH_PROP = ".pk.path";
 
+    private static final String CONNECTION_TIMEOUT_MILLIS_PROP = "connectionTimeoutMillis";
+    private static final long DEFAULT_TIMEOUT_MILLIS = 5000;
+
+    public static long extractTimeoutMillis(BundleContext bundleContext) {
+        String key = PREFIX_PROP + CONNECTION_TIMEOUT_MILLIS_PROP;
+        String timeoutString = bundleContext.getProperty(key);
+        if (timeoutString == null || timeoutString.length() == 0) {
+            return DEFAULT_TIMEOUT_MILLIS;
+        }
+        try {
+            return Long.parseLong(timeoutString);
+        }catch(NumberFormatException e) {
+            logger.warn("Cannot parse {} property: {}, using defaults", key, timeoutString, e);
+            return DEFAULT_TIMEOUT_MILLIS;
+        }
+    }
+
     public static InetSocketAddress extractTCPNetconfAddress(BundleContext context, String exceptionMessageIfNotFound, boolean forClient) {
 
         Optional<InetSocketAddress> inetSocketAddressOptional = extractSomeNetconfAddress(context, InfixProp.tcp, exceptionMessageIfNotFound, forClient);
@@ -32,7 +57,12 @@ public class NetconfConfigUtil {
         if (inetSocketAddressOptional.isPresent() == false) {
             throw new IllegalStateException("Netconf tcp address not found." + exceptionMessageIfNotFound);
         }
-        return inetSocketAddressOptional.get();
+        InetSocketAddress inetSocketAddress = inetSocketAddressOptional.get();
+        if (inetSocketAddress.getAddress().isAnyLocalAddress()) {
+            logger.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. " +
+                    "Consider changing {} to 127.0.0.1", PREFIX_PROP + InfixProp.tcp + ADDRESS_SUFFIX_PROP);
+        }
+        return inetSocketAddress;
     }
 
     public static Optional<InetSocketAddress> extractSSHNetconfAddress(BundleContext context, String exceptionMessage) {
index 00eacdfce6b9eba6fed4b472a95f4a265748877b..c265760b97d28ff95210822e7bb0bf02293af925 100644 (file)
@@ -373,11 +373,11 @@ one.lib.nav = {
 
 one.lib.helper = {
     parseInt : function(value) {
-        return (value !== null && value !== '') ?
+        return (value != null && value.trim() !== '') ?
             parseInt(value) : ''
     },
     parseFloat : function(value) {
-        return (value !== null && value !== '') ?
+        return (value != null && value.trim() !== '') ?
             parseFloat(value) : ''
     }
 }