<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
<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>
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 {
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"));
+ }
+ }
+
}
--- /dev/null
+<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
+++ /dev/null
-/*
- * 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);
- }
- }
-
-}
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;
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 {
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();
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);
+ }
}
<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>
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
<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>
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;
}
}
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;
}
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;
</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 -->
<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>
<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>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
- <version>0.6.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
- <version>0.6.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<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>
<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>
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);
<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>
*/
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;
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;
}
@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() {
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) {
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);
device.setSocketAddress(socketAddress);
device.setEventExecutor(getEventExecutorDependency());
- device.setDispatcher(createDispatcher());
+ device.setDispatcher(createDispatcher(clientConnectionTimeoutMillis));
device.setSchemaSourceProvider(getGlobalNetconfSchemaProvider(bundleContext));
getDomRegistryDependency().registerProvider(device, bundleContext);
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);
}
}
}
}
}
+
+ 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
<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>
+++ /dev/null
-/*
- * 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";
- }
-}
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;
/**
* 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";
@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:.+}")
+++ /dev/null
-/*
- * 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);
-
-}
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;
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;
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;
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;
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;
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;
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")
}
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)
}
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;
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)
}
}
- override createConfigurationDataLegacy(String identifier, CompositeNode payload) {
- createConfigurationData(identifier, payload);
- }
-
override createConfigurationData(String identifier, CompositeNode payload) {
if (payload.namespace === null) {
throw new ResponseException(BAD_REQUEST,
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;
* Test of json output when as input are specified composite node with empty
* data + YANG file
*/
- @Ignore
+
@Test
public void compositeNodeAndYangWithJsonReaderEmptyDataTest() {
CompositeNode compositeNode = prepareCompositeNodeWithEmpties();
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);
// :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();
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();
// :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();
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 {
dataLoad("/cnsn-to-json/identityref", 2, "identityref-module", "cont");
}
- @Ignore
@Test
public void identityrefToJsonTest() {
String json = null;
assertTrue(mtch.matches());
}
- @Ignore
@Test
public void identityrefToJsonWithoutQNameTest() {
String json = null;
}
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);
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;
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\": \"\""));
}
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;
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("^");
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(".*");
}
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;
}
@BeforeClass
public static void initialization() throws URISyntaxException {
- dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+ dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
@Test
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 {
+ ":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;
}
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);
+ }
+
}
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));
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;
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;
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}".
*/
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;
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.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;
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);
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;
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;
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 {
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);
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;
@BeforeClass
public static void initialize() {
- dataLoad("/instanceidentifier/yang", 3, "instance-identifier-module", "cont");
+ dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
@Test
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
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);
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);
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;
+ }
+
}
--- /dev/null
+{
+ "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
--- /dev/null
+<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>
--- /dev/null
+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
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(
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;
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)
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
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;
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);
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 {}",
}
- 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
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;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.util.regex.Pattern;
-import java.util.concurrent.TimeUnit;
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";
private volatile ConfigPersisterNotificationHandler jmxNotificationHandler;
- private volatile NetconfClient netconfClient;
private Thread initializationThread;
- private EventLoopGroup nettyThreadgroup;
+ private EventLoopGroup nettyThreadGroup;
private PersisterAggregator persisterAggregator;
@Override
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
@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");
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();
}
}
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;
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 {
}
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);
} 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));
}
}
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;
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 {
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,
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) {
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;
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() {
}
NetconfSessionPreferences proposal = new NetconfSessionPreferences(helloMessage);
return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
- sessionListenerFactory.getSessionListener());
+ sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
}
}
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;
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 {
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,
nettyThreadgroup = new NioEventLoopGroup();
netconfClientDispatcher = new NetconfSshClientDispatcher(new LoginPassword(
System.getProperty("username"), System.getProperty("password")),
- nettyThreadgroup, nettyThreadgroup);
+ nettyThreadgroup, nettyThreadgroup, 5000);
}
@Test
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;
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> {
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
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() {
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
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());
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;
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;
@Mock
private SessionMonitoringService monitoring;
+ HashedWheelTimer hashedWheelTimer;
+
@Before
public void setUp() throws Exception {
{ // init mocks
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());
s.await();
}
- @AfterClass
- public static void tearDownStatic() {
+ @After
+ public void tearDown(){
+ hashedWheelTimer.stop();
nettyGroup.shutdownGracefully();
}
@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);
private EventLoopGroup nettyGroup;
private NetconfServerDispatcher dispatch;
private DefaultCommitNotificationProducer commitNot;
+ private HashedWheelTimer hashedWheelTimer;
@Before
public void setUp() throws Exception {
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);
@After
public void tearDown() throws Exception {
+ hashedWheelTimer.stop();
commitNot.close();
nettyGroup.shutdownGracefully();
}
--- /dev/null
+/*
+ * 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();
+ }
+
+}
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;
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;
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;
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(
.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 {
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 {
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");
+ }
}
}
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;
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
commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
- nettyThreadgroup = new NioEventLoopGroup();
dispatchS = createDispatcher(factoriesListener);
ChannelFuture s = dispatchS.createServer(tlsAddress);
}
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,
@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)) {
}
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;
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;
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;
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
closeSession, startExi, stopExi;
private DefaultCommitNotificationProducer commitNot;
private NetconfServerDispatcher dispatch;
- private EventLoopGroup nettyThreadgroup;
private NetconfClientDispatcher clientDispatcher;
NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
- nettyThreadgroup = new NioEventLoopGroup();
commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
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() {
@After
public void tearDown() throws Exception {
commitNot.close();
- nettyThreadgroup.shutdownGracefully();
clientDispatcher.close();
}
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;
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;
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);
@Mock
private DefaultCommitNotificationProducer commitNot;
private NetconfServerDispatcher dispatch;
- private EventLoopGroup nettyThreadgroup;
private NetconfClientDispatcher clientDispatcher;
.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 {
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) {
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";
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
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);
}
}
}
- }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
+ }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
sendMessage(helloMessage);
changeState(State.OPEN_WAIT);
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);
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);
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
}
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);
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) {
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) : ''
}
}