<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netconf-connector</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-all</artifactId>
</dependencyManagement>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>netconf-auth</artifactId>
<artifactId>aaa-authn-odl-plugin</artifactId>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
<name>OpenDaylight :: AAA :: ODL NETCONF Plugin</name>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-auth</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Red Hat, Inc. and others.
-
- 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
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.0.2</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>odl-config-netconf-connector</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: Netconf :: Connector</name>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>netconf-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-manager</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-netconf-netty-util</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-netconf-notifications-impl</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netconf-connector</artifactId>
- </dependency>
- </dependencies>
-</project>
<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netconf-connector</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-netty-util</artifactId>
<classifier>features</classifier>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
<dependencyManagement>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>mdsal-model-artifacts</artifactId>
</dependencyManagement>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-util</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>odl-mdsal-models</artifactId>
<packaging>feature</packaging>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-all</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-netty-util</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
<name>OpenDaylight :: Netconf :: Impl</name>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-api</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <!-- Netconf server without config connector is just an empty shell -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netconf-connector</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <!-- Netconf will not provide schemas without monitoring -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager-facade-xml</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-monitoring</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
</dependencyManagement>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-all</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-all</artifactId>
<artifactId>mdsal-netconf-impl</artifactId>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
<name>OpenDaylight :: Netconf :: Notification :: Api</name>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-manager-facade-xml</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-tcp</artifactId>
<module>features-netconf</module>
<module>odl-aaa-netconf-plugin</module>
<module>odl-aaa-netconf-plugin-no-cluster</module>
- <module>odl-config-netconf-connector</module>
<module>odl-netconf-all</module>
<module>odl-netconf-api</module>
<module>odl-netconf-client</module>
<type>xml</type>
<classifier>features</classifier>
</dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-servlet</artifactId>
+ </dependency>
+
</dependencies>
</project>
</dependency>
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
</project>
<scope>test</scope>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
// look for the Base64 encoded part of the line to decode
// both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
- bytes = Base64.getDecoder().decode(keyLine.getBytes());
+ bytes = Base64.getDecoder().decode(keyLine.getBytes(StandardCharsets.UTF_8));
if (bytes.length == 0) {
throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
}
private String decodeType() {
int len = decodeInt();
- String type = new String(bytes, pos, len);
+ String type = new String(bytes, pos, len, StandardCharsets.UTF_8);
pos += len;
return type;
}
}
public static String encodePublicKey(final PublicKey publicKey) throws IOException {
- String publicKeyEncoded;
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
- if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) {
+ if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA) && publicKey instanceof RSAPublicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_RSA.getBytes().length);
- dout.write(KEY_TYPE_RSA.getBytes());
+ dout.writeInt(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8));
dout.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
dout.write(rsaPublicKey.getPublicExponent().toByteArray());
dout.writeInt(rsaPublicKey.getModulus().toByteArray().length);
dout.write(rsaPublicKey.getModulus().toByteArray());
- } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA)) {
+ } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA) && publicKey instanceof DSAPublicKey) {
DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
DSAParams dsaParams = dsaPublicKey.getParams();
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_DSA.getBytes().length);
- dout.write(KEY_TYPE_DSA.getBytes());
+ dout.writeInt(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8));
dout.writeInt(dsaParams.getP().toByteArray().length);
dout.write(dsaParams.getP().toByteArray());
dout.writeInt(dsaParams.getQ().toByteArray().length);
dout.write(dsaParams.getG().toByteArray());
dout.writeInt(dsaPublicKey.getY().toByteArray().length);
dout.write(dsaPublicKey.getY().toByteArray());
- } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA)) {
+ } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA) && publicKey instanceof BCECPublicKey) {
BCECPublicKey ecPublicKey = (BCECPublicKey) publicKey;
DataOutputStream dout = new DataOutputStream(byteOs);
- dout.writeInt(KEY_TYPE_ECDSA.getBytes().length);
- dout.write(KEY_TYPE_ECDSA.getBytes());
- dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length);
- dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes());
+ dout.writeInt(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8));
+ dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8).length);
+ dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8));
byte[] coordX = ecPublicKey.getQ().getAffineXCoord().getEncoded();
byte[] coordY = ecPublicKey.getQ().getAffineYCoord().getEncoded();
} else {
throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
}
- publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray()));
- return publicKeyEncoded;
+ return Base64.getEncoder().encodeToString(byteOs.toByteArray());
}
}
<artifactId>mockito-core</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
abstract class BaseCallHomeTopology extends AbstractNetconfTopology {
-
- protected DOMMountPointService mountPointService = null;
-
BaseCallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
final EventExecutor eventExecutor,
final ScheduledThreadPool keepaliveExecutor,
super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService,
encryptionService);
- this.mountPointService = mountPointService;
}
}
return remoteAddress.toString();
}
- private class DeviceConfig implements DataTreeChangeListener<Device> {
+ private static class DeviceConfig implements DataTreeChangeListener<Device> {
private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
}
}
- private class DeviceOp implements DataTreeChangeListener<Device> {
+ private static class DeviceOp implements DataTreeChangeListener<Device> {
private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
}
}
- private class GlobalConfig implements DataTreeChangeListener<Global> {
+ private static class GlobalConfig implements DataTreeChangeListener<Global> {
private volatile Global current = null;
}
}
- private final String path;
private Properties properties;
public Configuration() {
- path = "<no-path>";
properties = new Properties();
}
public Configuration(final String path) throws ConfigurationException {
- this.path = path;
try {
this.properties = readFromPath(path);
} catch (IOException ioe) {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (c) 2016 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
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>netconf-parent</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <relativePath>../netconf-parent</relativePath>
- </parent>
-
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>config-netconf-connector</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- <name>${project.artifactId}</name>
- <packaging>bundle</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <!-- compile dependencies -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager-facade-xml</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-mapping-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-notifications-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-util</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-util</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.opendaylight.netconf.confignetconfconnector.osgi.Activator</Bundle-Activator>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /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.netconf.confignetconfconnector.operations;
-
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
-
-public abstract class AbstractConfigNetconfOperation extends AbstractLastNetconfOperation {
-
- private final ConfigSubsystemFacade configSubsystemFacade;
-
- protected AbstractConfigNetconfOperation(ConfigSubsystemFacade configSubsystemFacade,
- String netconfSessionIdForReporting) {
- super(netconfSessionIdForReporting);
- this.configSubsystemFacade = configSubsystemFacade;
- }
-
- public ConfigSubsystemFacade getConfigSubsystemFacade() {
- return configSubsystemFacade;
- }
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class Commit extends AbstractConfigNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(Commit.class);
-
- public Commit(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- private static void checkXml(XmlElement xml) throws DocumentedException {
- xml.checkName(XmlNetconfConstants.COMMIT);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- }
-
- @Override
- protected String getOperationName() {
- return XmlNetconfConstants.COMMIT;
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
-
- checkXml(xml);
- CommitStatus status;
- try {
- status = getConfigSubsystemFacade().commitTransaction();
- LOG.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
- } catch (ConflictingVersionException | ValidationException e) {
- throw DocumentedException.wrap(e);
- }
- LOG.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
-
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- }
-
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import com.google.common.base.Optional;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-
-public class DiscardChanges extends AbstractConfigNetconfOperation {
-
- public static final String DISCARD = "discard-changes";
-
- private static final Logger LOG = LoggerFactory.getLogger(DiscardChanges.class);
-
- public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade,
- final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- private static void fromXml(final XmlElement xml) throws DocumentedException {
- xml.checkName(DISCARD);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- }
-
- @Override
- protected String getOperationName() {
- return DISCARD;
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- @Override
- protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement xml) throws DocumentedException {
- fromXml(xml);
- try {
- getConfigSubsystemFacade().abortConfiguration();
- } catch (final RuntimeException e) {
- LOG.warn("Abort failed: ", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo
- .put(ErrorTag.OPERATION_FAILED.name(),
- "Abort failed.");
- throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR, errorInfo);
- }
- LOG.trace("Changes discarded successfully from datastore {}", Datastore.candidate);
-
-
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- }
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * Simple Lock implementation that pretends to lock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed
- * (JMX is the only possible interference)
- */
-public class Lock extends AbstractLastNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(Lock.class);
-
- private static final String LOCK = "lock";
- private static final String TARGET_KEY = "target";
-
- public Lock(final String netconfSessionIdForReporting) {
- super(netconfSessionIdForReporting);
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement operationElement) throws DocumentedException {
- final Datastore targetDatastore = extractTargetParameter(operationElement);
- if (targetDatastore == Datastore.candidate) {
- // Since candidate datastore instances are allocated per session and not accessible anywhere else,
- // no need to lock
- LOG.debug("Locking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
- // TODO should this fail if we are already locked ?
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- }
-
- // Not supported running lock
- throw new DocumentedException("Unable to lock " + Datastore.running + " datastore",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
- }
-
- static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
- final XmlElement targetElement = operationElement.getOnlyChildElementWithSameNamespace(TARGET_KEY);
- final XmlElement targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
-
- return Datastore.valueOf(targetChildNode.getName());
- }
-
- @Override
- protected String getOperationName() {
- return LOCK;
- }
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * Simple unlock implementation that pretends to unlock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed
- * (JMX is the only possible interference)
- */
-public class UnLock extends AbstractLastNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(UnLock.class);
-
- private static final String UNLOCK = "unlock";
-
- public UnLock(final String netconfSessionIdForReporting) {
- super(netconfSessionIdForReporting);
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement operationElement) throws DocumentedException {
- final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
- if (targetDatastore == Datastore.candidate) {
- // Since candidate datastore instances are allocated per session and not accessible anywhere else,
- // no need to lock
- LOG.debug("Unlocking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
- // TODO this should fail if we are not locked
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- }
-
- // Not supported running lock
- throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
- }
-
- @Override
- protected String getOperationName() {
- return UNLOCK;
- }
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import com.google.common.base.Optional;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class Validate extends AbstractConfigNetconfOperation {
-
- public static final String VALIDATE = "validate";
-
- private static final Logger LOG = LoggerFactory.getLogger(Validate.class);
-
- public Validate(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- private void checkXml(final XmlElement xml) throws DocumentedException {
- xml.checkName(VALIDATE);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
- final XmlElement sourceElement = xml.getOnlyChildElement(XmlNetconfConstants.SOURCE_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- final XmlElement sourceChildNode = sourceElement.getOnlyChildElement();
-
- sourceChildNode.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- final String datastoreValue = sourceChildNode.getName();
- final Datastore sourceDatastore = Datastore.valueOf(datastoreValue);
-
- if (sourceDatastore != Datastore.candidate) {
- throw new DocumentedException("Only " + Datastore.candidate
- + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.APPLICATION,
- ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
- }
- }
-
- @Override
- protected String getOperationName() {
- return VALIDATE;
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement xml) throws DocumentedException {
- checkXml(xml);
- try {
- getConfigSubsystemFacade().validateConfiguration();
- } catch (final ValidationException e) {
- LOG.warn("Validation failed", e);
- throw DocumentedException.wrap(e);
- } catch (final IllegalStateException e) {
- LOG.warn("Validation failed", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo
- .put(ErrorTag.OPERATION_FAILED.name(),
- "Datastore is not present. "
- + "Use 'get-config' or 'edit-config' before triggering 'operations' operation");
- throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR, errorInfo);
-
- }
-
- LOG.trace("Datastore {} validated successfully", Datastore.candidate);
-
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- }
-}
+++ /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.netconf.confignetconfconnector.operations.editconfig;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.facade.xml.ConfigExecution;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class EditConfig extends AbstractConfigNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
-
- private final EditConfigXmlParser editConfigXmlParser;
-
- public EditConfig(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- this.editConfigXmlParser = new EditConfigXmlParser();
- }
-
- @VisibleForTesting
- Element getResponseInternal(final Document document,
- final ConfigExecution configExecution) throws DocumentedException {
-
- try {
- getConfigSubsystemFacade().executeConfigExecution(configExecution);
- } catch (final ValidationException e) {
- LOG.warn("Test phase for {} failed", EditConfigXmlParser.EDIT_CONFIG, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.OPERATION_FAILED.name(), e.getMessage());
- throw new DocumentedException("Test phase: " + e.getMessage(), e, ErrorType.APPLICATION,
- ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR, errorInfo);
- }
-
- LOG.trace("Operation {} successful", EditConfigXmlParser.EDIT_CONFIG);
-
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
- }
-
- @Override
- protected String getOperationName() {
- return EditConfigXmlParser.EDIT_CONFIG;
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement xml) throws DocumentedException {
- // FIXME config mapping getter works on dynamic yang store service
- // and so does later executeConfigExecution method
- // They might have different view of current yangs in ODL and might cause race conditions
- final Config cfg = getConfigSubsystemFacade().getConfigMapping();
- final ConfigExecution configExecution = editConfigXmlParser.fromXml(xml, cfg);
-
- return getResponseInternal(document, configExecution);
- }
-
-}
+++ /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.netconf.confignetconfconnector.operations.editconfig;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.ConfigExecution;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.facade.xml.TestOption;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class EditConfigXmlParser {
-
- private static final Logger LOG = LoggerFactory.getLogger(EditConfigXmlParser.class);
-
- public static final String EDIT_CONFIG = "edit-config";
- public static final String DEFAULT_OPERATION_KEY = "default-operation";
- static final String ERROR_OPTION_KEY = "error-option";
- static final String DEFAULT_ERROR_OPTION = "stop-on-error";
- static final String TARGET_KEY = "target";
- static final String TEST_OPTION_KEY = "test-option";
-
- public EditConfigXmlParser() {
- }
-
- ConfigExecution fromXml(final XmlElement xml, final Config cfgMapping)
- throws DocumentedException {
-
- //TODO remove transactionProvider and CfgRegistry from parameters, accept only service ref store
-
- EditStrategyType editStrategyType = EditStrategyType.getDefaultStrategy();
-
- xml.checkName(EditConfigXmlParser.EDIT_CONFIG);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
-
- XmlElement targetElement;
- XmlElement targetChildNode;
- targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
- targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
-
- final String datastoreValue = targetChildNode.getName();
- final Datastore targetDatastore = Datastore.valueOf(datastoreValue);
- LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TARGET_KEY, targetDatastore);
-
- // check target
- if (targetDatastore != Datastore.candidate) {
- throw new DocumentedException(String.format(
- "Only %s datastore supported for edit config but was: %s",
- Datastore.candidate,
- targetDatastore),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
-
- // Test option
- final TestOption testOption;
- final Optional<XmlElement> testOptionElementOpt = xml
- .getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.TEST_OPTION_KEY);
- if (testOptionElementOpt.isPresent()) {
- final String testOptionValue = testOptionElementOpt.get().getTextContent();
- testOption = TestOption.getFromXmlName(testOptionValue);
- } else {
- testOption = TestOption.getDefault();
- }
- LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TEST_OPTION_KEY, testOption);
-
- // Error option
- final Optional<XmlElement> errorOptionElement = xml
- .getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.ERROR_OPTION_KEY);
- if (errorOptionElement.isPresent()) {
- final String errorOptionParsed = errorOptionElement.get().getTextContent();
- if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)) {
- throw new UnsupportedOperationException("Only " + EditConfigXmlParser.DEFAULT_ERROR_OPTION
- + " supported for " + EditConfigXmlParser.ERROR_OPTION_KEY + ", was " + errorOptionParsed);
- }
- }
-
- // Default op
- final Optional<XmlElement> defaultContent = xml
- .getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.DEFAULT_OPERATION_KEY);
- if (defaultContent.isPresent()) {
- final String mergeStrategyString = defaultContent.get().getTextContent();
- LOG.trace("Setting merge strategy to {}", mergeStrategyString);
- editStrategyType = EditStrategyType.valueOf(mergeStrategyString);
- }
-
- XmlElement configElement;
- configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
-
- return new ConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
- }
-}
+++ /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.netconf.confignetconfconnector.operations.get;
-
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class Get extends AbstractConfigNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(Get.class);
-
- public Get(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- private static void checkXml(XmlElement xml) throws DocumentedException {
- xml.checkName(XmlNetconfConstants.GET);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
- // Filter option: ignore for now, TODO only load modules specified by the filter
- }
-
- @Override
- protected String getOperationName() {
- return XmlNetconfConstants.GET;
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
- checkXml(xml);
- final Element element = getConfigSubsystemFacade().get(document);
- LOG.trace("{} operation successful", XmlNetconfConstants.GET);
- return element;
- }
-}
+++ /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.netconf.confignetconfconnector.operations.getconfig;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class GetConfig extends AbstractConfigNetconfOperation {
-
- public static final String GET_CONFIG = "get-config";
-
- private final Optional<String> maybeNamespace;
-
- private static final Logger LOG = LoggerFactory.getLogger(GetConfig.class);
-
- public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace,
- final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- this.maybeNamespace = maybeNamespace;
- }
-
- public static Datastore fromXml(XmlElement xml) throws DocumentedException {
-
- xml.checkName(GET_CONFIG);
- xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
- XmlElement sourceElement = xml.getOnlyChildElement(XmlNetconfConstants.SOURCE_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- XmlElement sourceNode = sourceElement.getOnlyChildElement();
- String sourceParsed = sourceNode.getName();
- LOG.debug("Setting source datastore to '{}'", sourceParsed);
-
- // Filter option: ignore for now, TODO only load modules specified by the filter
-
- return Datastore.valueOf(sourceParsed);
-
- }
-
- @Override
- protected String getOperationName() {
- return GET_CONFIG;
- }
-
- @Override
- public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
- return getConfigSubsystemFacade().getConfiguration(document, fromXml(xml), maybeNamespace);
- }
-}
+++ /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.netconf.confignetconfconnector.operations.runtimerpc;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.RpcFacade;
-import org.opendaylight.controller.config.facade.xml.rpc.InstanceRuntimeRpc;
-import org.opendaylight.controller.config.facade.xml.rpc.ModuleRpcs;
-import org.opendaylight.controller.config.facade.xml.rpc.Rpcs;
-import org.opendaylight.controller.config.facade.xml.rpc.RuntimeRpcElementResolved;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.netconf.mapping.api.HandlingPriority;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class RuntimeRpc extends AbstractConfigNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
-
- public RuntimeRpc(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- super(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
-
- @Override
- public HandlingPriority canHandle(Document message) throws DocumentedException {
- XmlElement requestElement = getRequestElementWithCheck(message);
-
- XmlElement operationElement = requestElement.getOnlyChildElement();
- final String netconfOperationName = operationElement.getName();
- final String netconfOperationNamespace;
- try {
- netconfOperationNamespace = operationElement.getNamespace();
- } catch (DocumentedException e) {
- LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
- return HandlingPriority.CANNOT_HANDLE;
- }
-
- final Optional<XmlElement> contextInstanceElement = operationElement
- .getOnlyChildElementOptionally(RpcFacade.CONTEXT_INSTANCE);
-
- if (!contextInstanceElement.isPresent()) {
- return HandlingPriority.CANNOT_HANDLE;
- }
-
- final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(contextInstanceElement.get()
- .getTextContent(), netconfOperationName, netconfOperationNamespace);
-
- // TODO reuse rpcs instance in fromXml method
- final Rpcs rpcs = getConfigSubsystemFacade().getRpcFacade().mapRpcs();
-
- try {
- final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
- final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(),
- netconfOperationName);
- Preconditions.checkState(instanceRuntimeRpc != null, "No rpc found for %s:%s", netconfOperationNamespace,
- netconfOperationName);
- } catch (IllegalStateException e) {
- LOG.debug("Cannot handle runtime operation {}:{}", netconfOperationNamespace, netconfOperationName, e);
- return HandlingPriority.CANNOT_HANDLE;
- }
-
- return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
- }
-
- @Override
- protected HandlingPriority canHandle(String netconfOperationName, String namespace) {
- throw new UnsupportedOperationException(
- "This should not be used since it is not possible to provide check with these attributes");
- }
-
- @Override
- protected String getOperationName() {
- throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
- }
-
- @Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
- // TODO check for namespaces and unknown elements
- final RpcFacade.OperationExecution execution = getConfigSubsystemFacade().getRpcFacade().fromXml(xml);
-
- LOG.debug("Invoking operation {} on {} with arguments {}", execution.getOperationName(), execution.getOn(),
- execution.getAttributes());
- final Object result = getConfigSubsystemFacade().getRpcFacade().executeOperation(execution);
-
- LOG.trace("Operation {} called successfully on {} with arguments {} with result {}",
- execution.getOperationName(), execution.getOn(), execution.getAttributes(), result);
-
- if (execution.isVoid()) {
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
- } else {
- return getConfigSubsystemFacade().getRpcFacade().toXml(document, result, execution);
- }
- }
-
-}
+++ /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.netconf.confignetconfconnector.osgi;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.netconf.api.util.NetconfConstants;
-import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class Activator implements BundleActivator {
-
- private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
-
- private ServiceRegistration<?> osgiRegistration;
-
- @Override
- public void start(final BundleContext context) throws Exception {
- ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory,
- ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer =
- new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
-
- @Override
- public ConfigSubsystemFacadeFactory addingService(
- ServiceReference<ConfigSubsystemFacadeFactory> reference) {
- LOG.debug("Got addingService(SchemaContextProvider) event");
- // Yang store service should not be registered multiple times
- ConfigSubsystemFacadeFactory configSubsystemFacade =
- reference.getBundle().getBundleContext().getService(reference);
- osgiRegistration = startNetconfServiceFactory(configSubsystemFacade, context);
- return configSubsystemFacade;
- }
-
- @Override
- public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
- ConfigSubsystemFacadeFactory service) {
- LOG.warn("Config manager facade was modified unexpectedly");
- }
-
- @Override
- public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
- ConfigSubsystemFacadeFactory service) {
- LOG.warn("Config manager facade was removed unexpectedly");
- }
- };
-
- ServiceTracker<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaContextProviderServiceTracker =
- new ServiceTracker<>(context, ConfigSubsystemFacadeFactory.class, schemaServiceTrackerCustomizer);
- schemaContextProviderServiceTracker.open();
- }
-
- @Override
- public void stop(final BundleContext bundleContext) throws Exception {
- if (osgiRegistration != null) {
- osgiRegistration.unregister();
- }
- }
-
- private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(
- final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
- final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory =
- new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
- // Add properties to autowire with netconf-impl instance for cfg subsystem
- final Dictionary<String, String> properties = new Hashtable<>();
- properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.CONFIG_NETCONF_CONNECTOR);
- return context.registerService(NetconfOperationServiceFactory.class,
- netconfOperationServiceFactory, properties);
- }
-
-}
+++ /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.netconf.confignetconfconnector.osgi;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
-import java.util.Set;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.netconf.confignetconfconnector.operations.Commit;
-import org.opendaylight.netconf.confignetconfconnector.operations.DiscardChanges;
-import org.opendaylight.netconf.confignetconfconnector.operations.Lock;
-import org.opendaylight.netconf.confignetconfconnector.operations.UnLock;
-import org.opendaylight.netconf.confignetconfconnector.operations.Validate;
-import org.opendaylight.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.get.Get;
-import org.opendaylight.netconf.confignetconfconnector.operations.getconfig.GetConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
-import org.opendaylight.netconf.mapping.api.NetconfOperation;
-
-final class NetconfOperationProvider {
- private final Set<NetconfOperation> operations;
-
- NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade,
- final String netconfSessionIdForReporting) {
-
- operations = setUpOperations(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- Set<NetconfOperation> getOperations() {
- return operations;
- }
-
- private static Set<NetconfOperation> setUpOperations(final ConfigSubsystemFacade configSubsystemFacade,
- String netconfSessionIdForReporting) {
- Set<NetconfOperation> ops = Sets.newHashSet();
-
- GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.absent(), netconfSessionIdForReporting);
-
- ops.add(getConfigOp);
- ops.add(new EditConfig(configSubsystemFacade, netconfSessionIdForReporting));
- ops.add(new Commit(configSubsystemFacade, netconfSessionIdForReporting));
- ops.add(new Lock(netconfSessionIdForReporting));
- ops.add(new UnLock(netconfSessionIdForReporting));
- ops.add(new Get(configSubsystemFacade, netconfSessionIdForReporting));
- ops.add(new DiscardChanges(configSubsystemFacade, netconfSessionIdForReporting));
- ops.add(new Validate(configSubsystemFacade, netconfSessionIdForReporting));
- ops.add(new RuntimeRpc(configSubsystemFacade, netconfSessionIdForReporting));
-
- return ops;
- }
-
-}
+++ /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.netconf.confignetconfconnector.osgi;
-
-import java.util.Set;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.netconf.api.monitoring.CapabilityListener;
-import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
-
-public class NetconfOperationServiceFactoryImpl implements NetconfOperationServiceFactory {
-
- private final ConfigSubsystemFacadeFactory configFacadeFactory;
-
- public NetconfOperationServiceFactoryImpl(ConfigSubsystemFacadeFactory configFacadeFactory) {
- this.configFacadeFactory = configFacadeFactory;
- }
-
- @Override
- public NetconfOperationServiceImpl createService(String netconfSessionIdForReporting) {
- return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting),
- netconfSessionIdForReporting);
- }
-
- @Override
- public Set<Capability> getCapabilities() {
- return configFacadeFactory.getCurrentCapabilities();
- }
-
- @Override
- public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- return configFacadeFactory.getYangStoreService().registerModuleListener(listener::onCapabilitiesChanged);
- }
-}
+++ /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.netconf.confignetconfconnector.osgi;
-
-import java.util.Set;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.netconf.mapping.api.NetconfOperationService;
-
-public class NetconfOperationServiceImpl implements NetconfOperationService {
-
- private final NetconfOperationProvider operationProvider;
- private final ConfigSubsystemFacade configSubsystemFacade;
-
- public NetconfOperationServiceImpl(final ConfigSubsystemFacade configSubsystemFacade,
- final String netconfSessionIdForReporting) {
- this.configSubsystemFacade = configSubsystemFacade;
- this.operationProvider = new NetconfOperationProvider(configSubsystemFacade, netconfSessionIdForReporting);
- }
-
- @Override
- public Set<NetconfOperation> getNetconfOperations() {
- return operationProvider.getOperations();
- }
-
- @Override
- public void close() {
- configSubsystemFacade.close();
- }
-
-}
+++ /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.netconf.confignetconfconnector;
-
-import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.opendaylight.controller.config.util.xml.XmlUtil.readXmlToElement;
-import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElement;
-import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import io.netty.channel.Channel;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.net.URISyntaxException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import javax.xml.parsers.ParserConfigurationException;
-import org.custommonkey.xmlunit.AbstractNodeTester;
-import org.custommonkey.xmlunit.NodeTest;
-import org.custommonkey.xmlunit.NodeTestException;
-import org.custommonkey.xmlunit.NodeTester;
-import org.custommonkey.xmlunit.XMLAssert;
-import org.custommonkey.xmlunit.XMLUnit;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
-import org.opendaylight.controller.config.yang.test.impl.ComplexList;
-import org.opendaylight.controller.config.yang.test.impl.Deep;
-import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
-import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
-import org.opendaylight.controller.config.yang.test.impl.DtoC;
-import org.opendaylight.controller.config.yang.test.impl.DtoD;
-import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
-import org.opendaylight.controller.config.yang.test.impl.Peers;
-import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.netconf.confignetconfconnector.operations.Commit;
-import org.opendaylight.netconf.confignetconfconnector.operations.DiscardChanges;
-import org.opendaylight.netconf.confignetconfconnector.operations.Lock;
-import org.opendaylight.netconf.confignetconfconnector.operations.UnLock;
-import org.opendaylight.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.get.Get;
-import org.opendaylight.netconf.confignetconfconnector.operations.getconfig.GetConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
-import org.opendaylight.netconf.impl.NetconfServerSession;
-import org.opendaylight.netconf.impl.NetconfServerSessionListener;
-import org.opendaylight.netconf.impl.mapping.operations.DefaultCloseSession;
-import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
-import org.opendaylight.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
-import org.opendaylight.netconf.util.test.XmlFileLoader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-import org.w3c.dom.traversal.DocumentTraversal;
-import org.xml.sax.SAXException;
-
-
-public class NetconfMappingTest extends AbstractConfigTest {
- private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
-
- private static final String INSTANCE_NAME = "instance-from-code";
- private static final String NETCONF_SESSION_ID = "foo";
- private static final String TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
- private NetconfTestImplModuleFactory factory;
- private DepTestImplModuleFactory factory2;
- private IdentityTestModuleFactory factory3;
- private TestImplModuleFactory factory4;
-
- @Mock
- YangStoreService yangStoreSnapshot;
- @Mock
- NetconfOperationRouter netconfOperationRouter;
- @Mock
- AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
- @Mock
- private AutoCloseable sessionCloseable;
-
- private TransactionProvider transactionProvider;
-
- private ConfigSubsystemFacade configSubsystemFacade;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
-
- final Filter filter = mock(Filter.class);
- doReturn(filter).when(mockedContext).createFilter(anyString());
- doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
- doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
-
- doReturn(yangStoreSnapshot).when(yangStoreSnapshot).getCurrentSnapshot();
- doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
- doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
- doReturn(new EnumResolver() {
- @Override
- public String fromYang(final String enumType, final String enumYangValue) {
- return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
- "Unable to resolve enum value %s, for enum %s with mappings %s",
- enumYangValue, enumType, getEnumMapping());
- }
-
- @Override
- public String toYang(final String enumType, final String enumYangValue) {
- return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
- "Unable to resolve enum value %s, for enum %s with mappings %s",
- enumYangValue, enumType, getEnumMapping().inverse());
- }
- }).when(this.yangStoreSnapshot).getEnumResolver();
-
- this.factory = new NetconfTestImplModuleFactory();
- this.factory2 = new DepTestImplModuleFactory();
- this.factory3 = new IdentityTestModuleFactory();
- factory4 = new TestImplModuleFactory();
- doNothing().when(sessionCloseable).close();
-
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory,
- this.factory2, this.factory3, factory4));
-
- transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
-
- configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot,
- "mapping-test");
- }
-
- private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException,
- InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
- final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
-
- final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
- final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
- setModule(mxBean, transaction, instanceName + "_dep");
-
- int index = 1;
- for (final Class<? extends AbstractServiceInterface> serviceInterface :
- factory.getImplementedServiceIntefaces()) {
- final ServiceInterfaceAnnotation annotation =
- serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
- transaction.saveServiceReference(
- transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
- "ref_from_code_to_" + instanceName + "_" + index++, on);
-
- }
- transaction.commit();
- return on;
- }
-
- @Test
- public void testIdentityRefs() throws Exception {
- edit("netconfMessages/editConfig_identities.xml");
-
- commit();
- Document configRunning = getConfigRunning();
- String asString = XmlUtil.toString(configRunning);
- assertThat(asString, containsString("test-identity2"));
- assertThat(asString, containsString("test-identity1"));
- assertEquals(2, countSubstringOccurence(asString, "</identities>"));
-
- edit("netconfMessages/editConfig_identities_inner_replace.xml");
- commit();
- configRunning = getConfigRunning();
- asString = XmlUtil.toString(configRunning);
- // test-identity1 was removed by replace
- assertThat(asString, not(containsString("test-identity2")));
- // now only 1 identities entry is present
- assertEquals(1, countSubstringOccurence(asString, "</identities>"));
- }
-
- private static int countSubstringOccurence(final String string, final String substring) {
- final Matcher matches = Pattern.compile(substring).matcher(string);
- int count = 0;
- while (matches.find()) {
- count++;
- }
- return count;
- }
-
- @Override
- protected BindingRuntimeContext getBindingRuntimeContext() {
- final BindingRuntimeContext ret = super.getBindingRuntimeContext();
- doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
- doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
- doReturn(getSchemaContext()).when(ret).getSchemaContext();
- return ret;
- }
-
- @Test
- public void testServicePersistance() throws Exception {
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- Document config = getConfigCandidate();
- assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
- "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
- "ref_from_code_to_instance-from-code_1"));
-
-
- edit("netconfMessages/editConfig_addServiceName.xml");
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
- "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
- "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
-
- edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
- "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
- "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
-
- commit();
- config = getConfigRunning();
- assertCorrectRefNamesForDependencies(config);
- assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
- "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
- "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
-
- edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
- "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
- "ref_from_code_to_instance-from-code_1"));
-
- try {
- edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
- fail("Should've failed, non-existing service instance");
- } catch (final DocumentedException e) {
- assertEquals(e.getErrorSeverity(), DocumentedException.ErrorSeverity.ERROR);
- assertEquals(e.getErrorTag(), DocumentedException.ErrorTag.OPERATION_FAILED);
- assertEquals(e.getErrorType(), DocumentedException.ErrorType.APPLICATION);
- }
-
- edit("netconfMessages/editConfig_replace_default.xml");
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Collections.<String>emptySet());
-
- edit("netconfMessages/editConfig_remove.xml");
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Collections.<String>emptySet());
-
- commit();
- config = getConfigCandidate();
- assertCorrectServiceNames(config, Collections.<String>emptySet());
-
- }
-
- @Test
- public void testUnLock() throws Exception {
- assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
- assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
- }
-
- private static void assertCorrectRefNamesForDependencies(final Document config) throws NodeTestException {
- final NodeList modulesList = config.getElementsByTagName("modules");
- assertEquals(1, modulesList.getLength());
-
- final NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
- final NodeTester tester = new AbstractNodeTester() {
- private int defaultRefNameCount = 0;
- private int userRefNameCount = 0;
-
- @Override
- public void testText(final Text text) throws NodeTestException {
- if (text.getData().equals("ref_dep2")) {
- defaultRefNameCount++;
- } else if (text.getData().equals("ref_dep_user_two")) {
- userRefNameCount++;
- }
- }
-
- @Override
- public void noMoreNodes(final NodeTest forTest) throws NodeTestException {
- assertEquals(0, defaultRefNameCount);
- assertEquals(2, userRefNameCount);
- }
- };
- nt.performTest(tester, Node.TEXT_NODE);
- }
-
- private static void assertCorrectServiceNames(final Document configCandidate,
- final Set<String> refNames) throws NodeTestException {
- final Set<String> refNames2 = new HashSet<>(refNames);
- final NodeList servicesNodes = configCandidate.getElementsByTagName("services");
- assertEquals(1, servicesNodes.getLength());
-
- final NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
- final NodeTester tester = new AbstractNodeTester() {
-
- @Override
- public void testElement(final Element element) throws NodeTestException {
- if (element.getNodeName() != null) {
- if (element.getNodeName().equals("name")) {
- final String elmText = element.getTextContent();
- if (refNames2.contains(elmText)) {
- refNames2.remove(elmText);
- } else {
- throw new NodeTestException("Unexpected services defined: " + elmText);
- }
- }
- }
- }
-
- @Override
- public void noMoreNodes(final NodeTest forTest) throws NodeTestException {
- assertEquals(Collections.<String>emptySet(), refNames2);
- assertTrue(refNames2.toString(), refNames2.isEmpty());
- }
- };
- nt.performTest(tester, Node.ELEMENT_NODE);
- }
-
- @Test
- public void testConfigNetconfUnionTypes() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- commit();
- Document response = getConfigRunning();
- final Element ipElement = readXmlToElement(
- "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
- assertContainsElement(response, readXmlToElement(
- "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
-
- assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
-
-
- edit("netconfMessages/editConfig_setUnions.xml");
- commit();
- response = getConfigRunning();
- assertContainsElement(response, readXmlToElement(
- "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
- assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">"
- + "randomStringForUnion</union-test-attr>"));
-
- }
-
- @Test
- public void testConfigNetconf() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- final Document configCandidate = getConfigCandidate();
- checkBinaryLeafEdited(configCandidate);
-
-
- // default-operation:none, should not affect binary leaf
- edit("netconfMessages/editConfig_none.xml");
- checkBinaryLeafEdited(getConfigCandidate());
-
- // check after edit
- commit();
- final Document response = getConfigRunning();
-
- checkBinaryLeafEdited(response);
- checkTypeConfigAttribute(response);
- checkTypedefs(response);
- checkTestingDeps(response);
- checkEnum(response);
- checkBigDecimal(response);
-
- edit("netconfMessages/editConfig_remove.xml");
-
- commit();
- assertXMLEqual(getConfigCandidate(), getConfigRunning());
-
- final Document expectedResult =
- XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
- XMLUnit.setIgnoreWhitespace(true);
- assertXMLEqual(expectedResult, getConfigRunning());
- assertXMLEqual(expectedResult, getConfigCandidate());
-
- edit("netconfMessages/editConfig_none.xml");
- closeSession();
- verify(sessionCloseable).close();
- verifyNoMoreInteractions(netconfOperationRouter);
- verifyNoMoreInteractions(netconfOperationServiceSnapshot);
- }
-
- private static void checkBigDecimal(final Document response) throws NodeTestException, SAXException, IOException {
- assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
- // Default
- assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
- }
-
- private void closeSession() throws ParserConfigurationException, SAXException,
- IOException, DocumentedException {
- final Channel channel = mock(Channel.class);
- doReturn("channel").when(channel).toString();
- final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
- final NetconfServerSession session =
- new NetconfServerSession(listener, channel, 1L,
- NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
- final DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
- closeOp.setNetconfSession(session);
- executeOp(closeOp, "netconfMessages/closeSession.xml");
- }
-
- private void edit(final String resource) throws ParserConfigurationException, SAXException, IOException,
- DocumentedException {
- final EditConfig editOp = new EditConfig(configSubsystemFacade, NETCONF_SESSION_ID);
- executeOp(editOp, resource);
- }
-
- private void commit() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
- final Commit commitOp = new Commit(configSubsystemFacade, NETCONF_SESSION_ID);
- executeOp(commitOp, "netconfMessages/commit.xml");
- }
-
- private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException,
- DocumentedException {
- final Lock commitOp = new Lock(NETCONF_SESSION_ID);
- return executeOp(commitOp, "netconfMessages/lock.xml");
- }
-
- private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException,
- DocumentedException {
- final UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
- return executeOp(commitOp, "netconfMessages/unlock.xml");
- }
-
- private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
- DocumentedException {
- final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
- NETCONF_SESSION_ID);
- return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
- }
-
- private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
- DocumentedException {
- final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
- NETCONF_SESSION_ID);
- return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
- }
-
- @Ignore("second edit message corrupted")
- @Test(expected = DocumentedException.class)
- public void testConfigNetconfReplaceDefaultEx() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- edit("netconfMessages/editConfig_replace_default_ex.xml");
- }
-
- @Test
- public void testConfigNetconfReplaceDefault() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- commit();
- Document response = getConfigRunning();
- final int allInstances = response.getElementsByTagName("module").getLength();
-
- edit("netconfMessages/editConfig_replace_default.xml");
-
- commit();
- response = getConfigRunning();
-
- final int afterReplace = response.getElementsByTagName("module").getLength();
- assertEquals(4, allInstances);
- assertEquals(2, afterReplace);
- }
-
- @Test
- public void testSameAttrDifferentNamespaces() throws Exception {
- try {
- edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
- fail();
- } catch (final DocumentedException e) {
- final String message = e.getMessage();
- assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
- assertContainsString(message, TEST_NAMESPACE);
- assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- }
- }
-
- @Test
- public void testDifferentNamespaceInTO() throws Exception {
- try {
- edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
- fail();
- } catch (final DocumentedException e) {
- final String message = e.getMessage();
- assertContainsString(message, "Unrecognised elements");
- assertContainsString(message, "simple-int2");
- assertContainsString(message, "dto_d");
- }
- }
-
- @Test
- public void testSameAttrDifferentNamespacesList() throws Exception {
- try {
- edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
- fail();
- } catch (final DocumentedException e) {
- final String message = e.getMessage();
- assertContainsString(message, "Element allow-user present multiple times with different namespaces");
- assertContainsString(message, TEST_NAMESPACE);
- assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- }
- }
-
- @Test
- public void testTypeNameConfigAttributeMatching() throws Exception {
- edit("netconfMessages/editConfig.xml");
- commit();
- edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
- commit();
-
- final Document response = getConfigRunning();
- checkTypeConfigAttribute(response);
- }
-
- // TODO add <modules operation="replace"> functionality
- @Test(expected = DocumentedException.class)
- public void testConfigNetconfReplaceModuleEx() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- edit("netconfMessages/editConfig_replace_module_ex.xml");
- }
-
- @Test
- public void testUnrecognisedConfigElements() throws Exception {
-
- final String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
- final int testsCount = 8;
-
- for (int i = 0; i < testsCount; i++) {
- final String file = String.format(format, i + 1);
- LOG.info("Reading {}", file);
- try {
- edit(file);
- } catch (final DocumentedException e) {
- assertContainsString(e.getMessage(), "Unrecognised elements");
- assertContainsString(e.getMessage(), "unknownAttribute");
- continue;
- }
- fail("Unrecognised test should throw exception " + file);
- }
- }
-
- @Test
- @Ignore
- // FIXME
- public void testConfigNetconfReplaceModule() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- commit();
- Document response = getConfigRunning();
- final int allInstances = response.getElementsByTagName("instance").getLength();
-
- edit("netconfMessages/editConfig_replace_module.xml");
-
- commit();
- response = getConfigRunning();
- final int afterReplace = response.getElementsByTagName("instance").getLength();
-
- assertEquals(4 + 4 /* Instances from services */, allInstances);
- assertEquals(3 + 3, afterReplace);
- }
-
- @Test
- public void testEx2() throws Exception {
- //check abort before tx creation
- assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
-
- //check abort after tx creation
- edit("netconfMessages/editConfig.xml");
- assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
- }
-
- @Test
- public void testFailedDiscardChangesAbort() throws Exception {
- final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
- doThrow(new RuntimeException("Mocked runtime exception, Abort has to fail")).when(facade).abortConfiguration();
-
- final DiscardChanges discardOp = new DiscardChanges(facade, NETCONF_SESSION_ID);
-
- try {
- executeOp(discardOp, "netconfMessages/discardChanges.xml");
- fail("Should've failed, abort on mocked is supposed to throw RuntimeException");
- } catch (final DocumentedException e) {
- assertTrue(e.getErrorTag() == DocumentedException.ErrorTag.OPERATION_FAILED);
- assertTrue(e.getErrorSeverity() == DocumentedException.ErrorSeverity.ERROR);
- assertTrue(e.getErrorType() == DocumentedException.ErrorType.APPLICATION);
- }
- }
-
- private Document discard() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
- final DiscardChanges discardOp = new DiscardChanges(configSubsystemFacade, NETCONF_SESSION_ID);
- return executeOp(discardOp, "netconfMessages/discardChanges.xml");
- }
-
- private static void checkBinaryLeafEdited(final Document response)
- throws NodeTestException, SAXException, IOException {
- assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
- assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
- }
-
- private static void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
-
- assertContainsElement(response, readXmlToElement(
- "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
- // Default
- assertContainsElement(response, readXmlToElement(
- "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
-
- assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
- // Default
- assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
-
- assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
- // Default
- assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
- + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
- }
-
- private static void assertContainsString(final String string, final String substring) {
- assertThat(string, containsString(substring));
- }
-
- private static void checkEnum(final Document response) throws Exception {
-
- final String expectedEnumContent = "two";
-
- XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
- getXpathForNetconfImplSubnode(INSTANCE_NAME, "extended-enum"),
- response);
- }
-
- private static void checkTestingDeps(final Document response) {
- final int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
- assertEquals(2, testingDepsSize);
- }
-
- private static String getXpathForNetconfImplSubnode(final String instanceName, final String subnode) {
- return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply"
- + "/urn:ietf:params:xml:ns:netconf:base:1.0:data"
- + "/urn:opendaylight:params:xml:ns:yang:controller:config:modules"
- + "/urn:opendaylight:params:xml:ns:yang:controller:config:module"
- + "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']"
- + "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf"
- + "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
- }
-
- private static void checkTypeConfigAttribute(final Document response) throws Exception {
-
- final Map<String, String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
- "test2", "default-string");
- for (final Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
- XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
- getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(), "type"),
- response);
- }
- }
-
- private static Map<String, Map<String, ModuleMXBeanEntry>> getMbes() {
-
- final SchemaContext schemaContext = getSchemaContext();
- final YangStoreService yangStoreService = new YangStoreService(() -> schemaContext,
- mock(SchemaSourceProvider.class));
- final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
- doReturn(schemaContext).when(bindingRuntimeContext).getSchemaContext();
- doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
- yangStoreService.refresh(bindingRuntimeContext);
- final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = new HashMap<>();
- mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
-
- return mBeanEntries;
- }
-
- private static BiMap<String, String> getEnumMapping() {
- final HashBiMap<String, String> enumBiMap = HashBiMap.create();
- // Enum constants mapping from yang -> Java and back
- enumBiMap.put("one", "One");
- enumBiMap.put("two", "Two");
- enumBiMap.put("version1", "Version1");
- enumBiMap.put("version2", "Version2");
- return enumBiMap;
- }
-
- private static Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() {
- return getSchemaContext().getModules();
- }
-
- @Test
- public void testConfigNetconfRuntime() throws Exception {
-
- createModule(INSTANCE_NAME);
-
- edit("netconfMessages/editConfig.xml");
- checkBinaryLeafEdited(getConfigCandidate());
-
- // check after edit
- commit();
- Document response = get();
-
- assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
- // data from state
- assertEquals(2, getElementsSize(response, "asdf"));
- // data from running config
- assertEquals(2, getElementsSize(response, "simple-short"));
-
- assertEquals(8, getElementsSize(response, "inner-running-data"));
- assertEquals(8, getElementsSize(response, "deep2"));
- assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
- assertEquals(8 * 4, getElementsSize(response, "deep3"));
- assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
- assertEquals(8, getElementsSize(response, "inner-running-data-additional",
- "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
- assertEquals(8, getElementsSize(response, "deep4"));
- // TODO assert keys
-
- final RuntimeRpc netconf = new RuntimeRpc(configSubsystemFacade, NETCONF_SESSION_ID);
-
- response = executeOp(netconf, "netconfMessages/rpc.xml");
- assertContainsElementWithText(response, "testarg1");
-
- response = executeOp(netconf, "netconfMessages/rpcInner.xml");
- final Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
- XMLUnit.setIgnoreWhitespace(true);
- XMLAssert.assertXMLEqual(expectedReplyOk, response);
-
- response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
- assertContainsElementWithText(response, "true");
-
- response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
- assertContainsElementWithText(response, "1");
- assertContainsElementWithText(response, "2");
- }
-
- private Document get() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
- final Get getOp = new Get(configSubsystemFacade, NETCONF_SESSION_ID);
- return executeOp(getOp, "netconfMessages/get.xml");
- }
-
- private static int getElementsSize(final Document response, final String elementName) {
- return response.getElementsByTagName(elementName).getLength();
- }
-
- private static int getElementsSize(final Document response, final String elementName, final String namespace) {
- return response.getElementsByTagNameNS(namespace, elementName).getLength();
- }
-
- private static Document executeOp(final NetconfOperation op,
- final String filename) throws ParserConfigurationException,
- SAXException, IOException, DocumentedException {
-
- final Document request = XmlFileLoader.xmlFileToDocument(filename);
-
- LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
- final HandlingPriority priority = op.canHandle(request);
-
- Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
-
- final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
- LOG.debug("Got response\n{}", XmlUtil.toString(response));
- return response;
- }
-
- private static SchemaContext getSchemaContext() {
- return YangParserTestUtils.parseYangResources(NetconfMappingTest.class,
- "/META-INF/yang/config@2013-04-05.yang", "/META-INF/yang/rpc-context@2013-06-17.yang",
- "/META-INF/yang/config-test@2013-06-13.yang", "/META-INF/yang/config-test-impl@2013-04-03.yang",
- "/META-INF/yang/test-types@2013-11-27.yang", "/META-INF/yang/test-groups@2014-12-08.yang",
- "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
- }
-
- private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction,
- final String depName)
- throws InstanceAlreadyExistsException, InstanceNotFoundException {
- mxBean.setSimpleInt((long) 44);
- mxBean.setBinaryLeaf(new byte[]{8, 7, 9});
- final DtoD dtob = getDtoD();
- mxBean.setDtoD(dtob);
- //
- final DtoC dtoa = getDtoC();
- mxBean.setDtoC(dtoa);
- mxBean.setSimpleBoolean(false);
- //
- final Peers p1 = new Peers();
- p1.setCoreSize(44L);
- p1.setPort("port1");
- p1.setSimpleInt3(456);
- final Peers p2 = new Peers();
- p2.setCoreSize(44L);
- p2.setPort("port23");
- p2.setSimpleInt3(456);
- mxBean.setPeers(Lists.<Peers>newArrayList(p1, p2));
- // //
- mxBean.setSimpleLong(454545L);
- mxBean.setSimpleLong2(44L);
- mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
- mxBean.setSimpleByte(new Byte((byte) 4));
- mxBean.setSimpleShort(new Short((short) 4));
- mxBean.setSimpleTest(545);
-
- mxBean.setComplexList(Lists.<ComplexList>newArrayList());
- mxBean.setSimpleList(Lists.<Integer>newArrayList());
-
- final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
- int index = 1;
- for (final Class<? extends AbstractServiceInterface> serviceInterface :
- factory2.getImplementedServiceIntefaces()) {
- final ServiceInterfaceAnnotation annotation =
- serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
- transaction.saveServiceReference(
- transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
- "ref_from_code_to_" + depName + "_" + index++, testingDepOn);
-
- }
- mxBean.setTestingDep(testingDepOn);
- }
-
- private static DtoD getDtoD() {
- final DtoD dtob = new DtoD();
- dtob.setSimpleInt1((long) 444);
- dtob.setSimpleInt2((long) 4444);
- dtob.setSimpleInt3(454);
- final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
- final Deep deep = new Deep();
- deep.setSimpleInt3(4);
- dtobInner.setDeep(deep);
- dtobInner.setSimpleInt3(44);
- dtobInner.setSimpleList(Lists.newArrayList(4));
- dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
- dtob.setSimpleList(Lists.newArrayList(4));
- return dtob;
- }
-
- private static DtoC getDtoC() {
- final DtoC dtoa = new DtoC();
- // dtoa.setSimpleArg((long) 55);
- final DtoAInner dtoAInner = new DtoAInner();
- final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
- dtoAInnerInner.setSimpleArg(456L);
- dtoAInner.setDtoAInnerInner(dtoAInnerInner);
- dtoAInner.setSimpleArg(44L);
- dtoa.setDtoAInner(dtoAInner);
- return dtoa;
- }
-
-}
+++ /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.netconf.confignetconfconnector;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Services.ServiceInstance;
-
-public class ServiceTrackerTest {
-
- @Test
- public void test() {
- Services.ServiceInstance serviceInstance = new ServiceInstance("module", "serviceInstance");
-
- String string = serviceInstance.toString();
-
- Services.ServiceInstance serviceInstance2 = Services.ServiceInstance.fromString(string);
-
- assertEquals(serviceInstance, serviceInstance2);
- }
-
-}
+++ /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.netconf.confignetconfconnector.operations;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.w3c.dom.Element;
-
-public class ValidateTest {
-
- public static final String NETCONF_SESSION_ID_FOR_REPORTING = "foo";
-
- @Test(expected = DocumentedException.class)
- public void test() throws Exception {
- final XmlElement xml = XmlElement.fromString("<abc></abc>");
- final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test(expected = DocumentedException.class)
- public void testNoSource() throws Exception {
- final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
- + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 + "\"/>");
- final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test(expected = DocumentedException.class)
- public void testNoNamespace() throws Exception {
- final XmlElement xml = XmlElement.fromString("<validate/>");
- final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test(expected = DocumentedException.class)
- public void testRunningSource() throws Exception {
-
- final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
- + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
- + "\"><source><running></running></source></validate>");
- final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test(expected = DocumentedException.class)
- public void testNoTransaction() throws Exception {
- final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
- + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
- + "\"><source><candidate/></source></validate>");
- final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
- doThrow(IllegalStateException.class).when(facade).validateConfiguration();
- final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test(expected = DocumentedException.class)
- public void testValidationException() throws Exception {
- final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
- + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
- + "\">><source><candidate/></source></validate>");
- final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
- doThrow(ValidationException.class).when(facade).validateConfiguration();
- final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
- validate.handleWithNoSubsequentOperations(null, xml);
- }
-
- @Test
- public void testValidation() throws Exception {
- final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
- + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
- + "\"><source><candidate/></source></validate>");
- final Element okElement = XmlUtil.readXmlToElement("<ok/>");
- final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
- doNothing().when(facade).validateConfiguration();
- final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
- Element ok = validate.handleWithNoSubsequentOperations(XmlUtil.newDocument(), xml);
- assertEquals(XmlUtil.toString(okElement), XmlUtil.toString(ok));
- }
-
-}
+++ /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.netconf.confignetconfconnector.operations.editconfig;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyMapOf;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
-import java.util.Collections;
-import java.util.Map;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.facade.xml.ConfigExecution;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.confignetconfconnector.operations.ValidateTest;
-
-public class EditConfigTest {
-
- @Mock
- private YangStoreService yangStoreSnapshot;
- @Mock
- private TransactionProvider provider;
- @Mock
- private ConfigRegistryClient configRegistry;
- @Mock
- private ConfigTransactionClient configTransactionClient;
- @Mock
- private ObjectName mockOn;
-
- private ConfigSubsystemFacade cfgFacade;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
- doReturn("mockON").when(mockOn).toString();
- doReturn(mockOn).when(provider).getTestTransaction();
- doNothing().when(provider).validateTestTransaction(any(ObjectName.class));
-
- doReturn(mockOn).when(provider).getTestTransaction();
- doNothing().when(provider).abortTestTransaction(any(ObjectName.class));
- doReturn(mockOn).when(provider).getOrCreateTransaction();
-
- doNothing().when(provider).wipeTestTransaction(any(ObjectName.class));
-
- doReturn(configTransactionClient).when(configRegistry).getConfigTransactionClient(any(ObjectName.class));
- doReturn("mockConfigTransactionClient").when(configTransactionClient).toString();
-
- doReturn(mockOn).when(configTransactionClient).lookupConfigBean(anyString(), anyString());
-
- cfgFacade = new ConfigSubsystemFacade(configRegistry, configRegistry, yangStoreSnapshot, provider);
- }
-
- @Test
- public void test() throws Exception {
- EditConfig edit = new EditConfig(cfgFacade, ValidateTest.NETCONF_SESSION_ID_FOR_REPORTING);
- EditConfigStrategy editStrat = mock(EditConfigStrategy.class);
-
- doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class,
- AttributeConfigElement.class),
- any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
-
- ConfigExecution editConfigExecution = mockExecution(editStrat);
-
- edit.getResponseInternal(XmlUtil.newDocument(), editConfigExecution);
-
- verify(provider).getTestTransaction();
- verify(provider).validateTestTransaction(mockOn);
- verify(provider).abortTestTransaction(mockOn);
-
- verify(provider).getOrCreateTransaction();
-
- // For every instance execute strat
- verify(editStrat, times(2/* Test */ + 2/* Set */ + 2/*Handle missing instance Test*/
- + 2 /*Handle missing instance Set*/)).executeConfiguration(anyString(),
- anyString(), anyMapOf(String.class, AttributeConfigElement.class),
- any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
- }
-
- private ConfigExecution mockExecution(EditConfigStrategy editStrat) throws Exception {
- ConfigExecution mock = mock(ConfigExecution.class);
- doReturn(getMapping(editStrat)).when(mock).getResolvedXmlElements(any(ConfigTransactionClient.class));
- doReturn(getMappingDefinition(editStrat)).when(mock).getModulesDefinition(any(ConfigTransactionClient.class));
- doReturn(EditStrategyType.merge).when(mock).getDefaultStrategy();
- doReturn(true).when(mock).shouldSet();
- doReturn(true).when(mock).shouldTest();
- doReturn(mockServices()).when(mock).getServiceRegistryWrapper(any(ConfigTransactionClient.class));
- doReturn(new Services()).when(mock).getServices();
- doReturn(XmlElement.fromDomElement(XmlUtil.readXmlToElement("<abc/>"))).when(mock).getConfigElement();
- return mock;
- }
-
- private Object getMappingDefinition(EditConfigStrategy editStrat) {
- final Map<String, Multimap<String, ModuleElementDefinition>> result = Maps.newHashMap();
-
- Multimap<String, ModuleElementDefinition> innerMultimap = HashMultimap.create();
- Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
-
- ModuleElementDefinition mockedDefinition = mock(ModuleElementDefinition.class);
- doReturn(editStrat).when(mockedDefinition).getEditStrategy();
- doReturn("i1").when(mockedDefinition).getInstanceName();
- innerMultimap.put("m1", mockedDefinition);
-
- ModuleElementDefinition mockedDefinition2 = mock(ModuleElementDefinition.class);
- doReturn(editStrat).when(mockedDefinition2).getEditStrategy();
- doReturn("i2").when(mockedDefinition2).getInstanceName();
- innerMultimap.put("m1", mockedDefinition2);
-
- result.put("n1", innerMultimap);
-
- return result;
- }
-
- private static ServiceReferenceReadableRegistry mockServiceRegistry() {
- ServiceReferenceReadableRegistry mock = mock(ServiceReferenceReadableRegistry.class);
- doReturn(
- Collections.emptyMap())
- .when(mock).getServiceMapping();
- doReturn("mockedServiceReg").when(mock).toString();
-
- return mock;
- }
-
- static ServiceRegistryWrapper mockServices() {
- return new ServiceRegistryWrapper(mockServiceRegistry());
- }
-
- private Map<String, Multimap<String, ModuleElementResolved>> getMapping(EditConfigStrategy editStrat) {
- final Map<String, Multimap<String, ModuleElementResolved>> result = Maps.newHashMap();
-
- Multimap<String, ModuleElementResolved> innerMultimap = HashMultimap.create();
- Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
-
- InstanceConfigElementResolved ice1 = mock(InstanceConfigElementResolved.class);
- doReturn(attributes).when(ice1).getConfiguration();
- doReturn(editStrat).when(ice1).getEditStrategy();
- innerMultimap.put("m1", new ModuleElementResolved("i1", ice1));
-
- InstanceConfigElementResolved ice2 = mock(InstanceConfigElementResolved.class);
- doReturn(attributes).when(ice2).getConfiguration();
- doReturn(editStrat).when(ice2).getEditStrategy();
- innerMultimap.put("m1", new ModuleElementResolved("i2", ice2));
-
- result.put("n1", innerMultimap);
-
- return result;
- }
-
- static Map<String, AttributeConfigElement> getSimpleAttributes() {
- final Map<String, AttributeConfigElement> attributes = Maps.newHashMap();
- AttributeConfigElement ace1 = mock(AttributeConfigElement.class);
- doReturn("abcd").when(ace1).getResolvedDefaultValue();
- doReturn(Optional.<String>of("abc")).when(ace1).getResolvedValue();
- doReturn("mockedAce1").when(ace1).toString();
- doReturn("jmxNameAce1").when(ace1).getJmxName();
- attributes.put("a1", ace1);
- return attributes;
- }
-
-}
+++ /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.netconf.confignetconfconnector.operations.editconfig;
-
-import static java.util.Arrays.asList;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.createReadOnlyModuleON;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-import java.util.List;
-import java.util.Map;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.strategy.MergeEditConfigStrategy;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModule;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
-
-public class MergeEditConfigStrategyTest extends AbstractConfigTest {
- private static final MultipleDependenciesModuleFactory FACTORY = new MultipleDependenciesModuleFactory();
- private static final String FACTORY_NAME = FACTORY.getImplementationName();
- public static final String PARENT = "parent";
- public static final String D1 = "d1";
- public static final String D2 = "d2";
- public static final String D3 = "d3";
-
- @Before
- public void setUp() throws Exception {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORY));
-
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName d1 = transaction.createModule(FACTORY_NAME, D1);
- ObjectName d2 = transaction.createModule(FACTORY_NAME, D2);
- ObjectName parent = transaction.createModule(FACTORY_NAME, PARENT);
- MultipleDependenciesModuleMXBean multipleDependenciesModuleMXBean = transaction.newMXBeanProxy(parent,
- MultipleDependenciesModuleMXBean.class);
- multipleDependenciesModuleMXBean.setTestingDeps(asList(d1, d2));
- transaction.createModule(FACTORY_NAME, D3);
- transaction.commit();
- }
-
- @Test
- public void testMergingOfObjectNames() throws Exception {
- final MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
- final ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- // add D3
-
- AttributeConfigElement attributeConfigElement = mock(AttributeConfigElement.class);
- doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(FACTORY_NAME, D3)}))
- .when(attributeConfigElement).getResolvedValue();
- doReturn("mocked").when(attributeConfigElement).toString();
- String attributeName = MultipleDependenciesModule.testingDepsJmxAttribute.getAttributeName();
- doReturn(attributeName).when(attributeConfigElement).getJmxName();
- Map<String, AttributeConfigElement> configuration = ImmutableMap.of(
- attributeName,
- attributeConfigElement);
-
- strategy.executeConfiguration(FACTORY_NAME, PARENT, configuration, transaction,
- mock(ServiceRegistryWrapper.class));
- transaction.commit();
-
- // parent's attribute should contain d1,d2,d3
- MultipleDependenciesModuleMXBean proxy = configRegistryClient.newMXBeanProxy(
- createReadOnlyModuleON(FACTORY_NAME, PARENT),
- MultipleDependenciesModuleMXBean.class);
- List<ObjectName> testingDeps = proxy.getTestingDeps();
- List<ObjectName> expected = asList(createReadOnlyModuleON(FACTORY_NAME, D1),
- createReadOnlyModuleON(FACTORY_NAME, D2),
- createReadOnlyModuleON(FACTORY_NAME, D3));
- assertEquals(expected, testingDeps);
- }
-}
+++ /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.netconf.confignetconfconnector.operations.editconfig;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.collect.Sets;
-import java.util.Map;
-import javax.management.Attribute;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.strategy.ReplaceEditConfigStrategy;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-
-public class ReplaceEditConfigStrategyTest {
-
- @Mock
- private ConfigTransactionClient ta;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- doNothing().when(ta).destroyModule(anyString(), anyString());
- doReturn(mockON()).when(ta).lookupConfigBean(anyString(), anyString());
- doNothing().when(ta).setAttribute(any(ObjectName.class), anyString(), any(Attribute.class));
- }
-
- @Test
- public void test() throws Exception {
- ReplaceEditConfigStrategy strat = new ReplaceEditConfigStrategy();
-
- Map<String, AttributeConfigElement> map = EditConfigTest.getSimpleAttributes();
-
- doReturn(Sets.newHashSet(mockON(), mockON())).when(ta).lookupConfigBeans();
-
- strat.executeConfiguration("m1", "i1", map, ta, EditConfigTest.mockServices());
-
- verify(ta).lookupConfigBean(anyString(), anyString());
- verify(ta).setAttribute(any(ObjectName.class), anyString(), any(Attribute.class));
- }
-
- ObjectName mockON() {
- ObjectName mock = mock(ObjectName.class);
- doReturn("mockON").when(mock).toString();
- return mock;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 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.netconf.confignetconfconnector.osgi;
-
-import static junit.framework.TestCase.assertTrue;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import java.util.Set;
-import org.junit.Test;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.netconf.confignetconfconnector.operations.Commit;
-import org.opendaylight.netconf.confignetconfconnector.operations.DiscardChanges;
-import org.opendaylight.netconf.confignetconfconnector.operations.Lock;
-import org.opendaylight.netconf.confignetconfconnector.operations.UnLock;
-import org.opendaylight.netconf.confignetconfconnector.operations.Validate;
-import org.opendaylight.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.get.Get;
-import org.opendaylight.netconf.confignetconfconnector.operations.getconfig.GetConfig;
-import org.opendaylight.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
-import org.opendaylight.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.netconf.mapping.api.NetconfOperationService;
-
-public class NetconfOperationServiceImplTest {
-
- @Test
- public void testOperationService() {
- final ConfigSubsystemFacade configSubsystemFacade = mock(ConfigSubsystemFacade.class);
- final NetconfOperationService netconfOperationService =
- new NetconfOperationServiceImpl(configSubsystemFacade, "reportingID");
-
- // testing operations in Set from NetconfOperationProvider
-
- Set<NetconfOperation> operations = netconfOperationService.getNetconfOperations();
-
- assertTrue(containInstance(operations, GetConfig.class));
- assertTrue(containInstance(operations, EditConfig.class));
- assertTrue(containInstance(operations, Commit.class));
- assertTrue(containInstance(operations, Lock.class));
- assertTrue(containInstance(operations, UnLock.class));
- assertTrue(containInstance(operations, Get.class));
- assertTrue(containInstance(operations, DiscardChanges.class));
- assertTrue(containInstance(operations, Validate.class));
- assertTrue(containInstance(operations, RuntimeRpc.class));
-
- // verify closing service
-
- doNothing().when(configSubsystemFacade).close();
- netconfOperationService.close();
-
- verify(configSubsystemFacade, times(1)).close();
- }
-
- private boolean containInstance(final Set<NetconfOperation> operations, final Class<?> cls) {
- return operations.stream().filter(cls::isInstance).findFirst().isPresent();
- }
-}
<artifactId>yang-data-codec-xml</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
-import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
listeners1.add(listener);
return () -> listeners1.remove(listener);
}
-}
\ No newline at end of file
+}
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.netconf.api.capability.Capability;
+import org.opendaylight.netconf.api.capability.YangModuleCapability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactoryListener;
import com.google.common.util.concurrent.CheckedFuture;
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
future.checkedGet();
} catch (final TransactionCommitFailedException e) {
LOG.debug("Transaction {} failed on", candidateTransaction, e);
- final String cause = e.getCause() != null ? (" Cause: " + e.getCause().getMessage()) : "";
+ final String cause = e.getCause() != null ? " Cause: " + e.getCause().getMessage() : "";
throw new DocumentedException(
"Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause, e,
ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
import java.util.Iterator;
import java.util.Map;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
import org.opendaylight.netconf.api.NetconfDocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.opendaylight.yangtools.yang.common.QName;
package org.opendaylight.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
package org.opendaylight.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import com.google.common.base.Optional;
import java.util.HashMap;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
import java.util.ListIterator;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.mdsal.connector.ops.DataTreeChangeTracker.DataTreeChange;
package org.opendaylight.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
import org.opendaylight.netconf.api.NetconfDocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
final Map<String, Attr> attributes = requestElement.getAttributes();
final Element response = handle(document, operationElement, subsequentOperation);
- final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+ final Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY,
Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
if (XmlElement.fromDomElement(response).hasNamespace()) {
private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
final SchemaPath rpcOutputPath) {
- final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
+ final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.RPC_REPLY_KEY));
final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
@Nullable
private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
throws DocumentedException {
- if (input.getChildNodes().isEmpty()) {
+ if (input == null || input.getChildNodes().isEmpty()) {
return null;
}
package org.opendaylight.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.ops.Datastore;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamWriter;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
package org.opendaylight.netconf.mdsal.connector.ops.get;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.mdsal.connector.ops.Datastore;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.mdsal.connector.ops.Datastore;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
new StreamResult(writer));
LOG.warn(writer.getBuffer().toString());
}
-}
\ No newline at end of file
+}
import static org.opendaylight.yangtools.yang.test.util.YangParserTestUtils.parseYangResources;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
import org.opendaylight.netconf.util.test.XmlFileLoader;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.w3c.dom.Document;
getTransactionProvider());
return executeOperation(copyConfig, resource);
}
-}
\ No newline at end of file
+}
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.netconf.mdsal.connector.ops.get.GetConfig;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.model.InitializationError;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-error=org.opendaylight.controller.config.util.xml.DocumentedException
+error=org.opendaylight.netconf.api.DocumentedException
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/choiceList
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/maincontent
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/choiceList
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/(urn:dummy:aug?revision=1999-08-17)augmented-leaf
-error=org.opendaylight.controller.config.util.xml.DocumentedException
+error=org.opendaylight.netconf.api.DocumentedException
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/choiceList/choiceList[{(urn:dummy:mod-0?revision=2016-03-01)name=aaa}]
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/multi-key-list
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/multi-key-list/multi-key-list[{(urn:dummy:mod-0?revision=2016-03-01)id1=aaa, (urn:dummy:mod-0?revision=2016-03-01)id2=bbb}]
success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/multi-key-list
-success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/inner/inner-multi-key-list/inner-multi-key-list[{(urn:dummy:mod-0?revision=2016-03-01)id1=aaa, (urn:dummy:mod-0?revision=2016-03-01)id2=bbb}]
\ No newline at end of file
+success=/(urn:dummy:mod-0?revision=2016-03-01)mainroot/inner/inner-multi-key-list/inner-multi-key-list[{(urn:dummy:mod-0?revision=2016-03-01)id1=aaa, (urn:dummy:mod-0?revision=2016-03-01)id2=bbb}]
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
</project>
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.sal.common.util.NoopAutoCloseable;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
netconfOperationServiceFactoryListener.onRemoveNetconfOperationServiceFactory(this);
}
-}
\ No newline at end of file
+}
</instructions>
</configuration>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
</project>
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.sal.common.util.NoopAutoCloseable;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
<artifactId>yang-test-util</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
<artifactId>hamcrest-core</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.messagebus.app.util.TopicDOMNotification;
import org.opendaylight.controller.messagebus.app.util.Util;
import org.opendaylight.controller.messagebus.spi.EventSource;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.util.NetconfUtil;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
.put(cntr.getNotificationUrnPrefix(), cntr);
Map<String, Stream> availableStreams = getAvailableStreams();
LOG.debug("Stream configuration compare...");
- for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
- final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
+ for (Entry<String, String> entry : this.urnPrefixToStreamMap.entrySet()) {
+ String urnPrefix = entry.getKey();
+ final String streamName = entry.getValue();
LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
if (availableStreams.containsKey(streamName)) {
LOG.debug("Stream containig on device");
}
}
- private void nodeUpdated(final InstanceIdentifier<?> key, final Node node) {
- Preconditions.checkNotNull(key);
- if (!validateNode(node)) {
- LOG.warn("NodeUpdated event : Node [{}] is null or not valid.", key.toString());
- return;
- }
-
- LOG.info("Netconf event source [{}] is updating...", key.toString());
- NetconfEventSourceRegistration nesr = registrationMap.get(key);
- if (nesr != null) {
- nesr.updateStatus();
- } else {
- nodeCreated(key, node);
- }
- }
-
private void nodeRemoved(final InstanceIdentifier<?> key) {
Preconditions.checkNotNull(key);
LOG.info("Netconf event source [{}] is removing...", key.toString());
<name>${project.artifactId}</name>
<packaging>bundle</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<groupId>${project.groupId}</groupId>
<artifactId>protocol-framework</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>ietf-inet-types-2013-07-15</artifactId>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>ietf-yang-types-20130715</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>mockito-configuration</artifactId>
</dependency>
+ <dependency>
+ <groupId>xmlunit</groupId>
+ <artifactId>xmlunit</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api;
+
+import static org.opendaylight.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
+import static org.opendaylight.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Checked exception to communicate an error that needs to be sent to the
+ * netconf client.
+ */
+public class DocumentedException extends Exception {
+
+ public static final String RPC_ERROR = "rpc-error";
+ public static final String ERROR_TYPE = "error-type";
+ public static final String ERROR_TAG = "error-tag";
+ public static final String ERROR_SEVERITY = "error-severity";
+ public static final String ERROR_APP_TAG = "error-app-tag";
+ public static final String ERROR_PATH = "error-path";
+ public static final String ERROR_MESSAGE = "error-message";
+ public static final String ERROR_INFO = "error-info";
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(DocumentedException.class);
+
+ private static final DocumentBuilderFactory BUILDER_FACTORY;
+
+ static {
+ BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
+ try {
+ BUILDER_FACTORY.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ BUILDER_FACTORY.setXIncludeAware(false);
+ BUILDER_FACTORY.setExpandEntityReferences(false);
+ } catch (final ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ BUILDER_FACTORY.setNamespaceAware(true);
+ BUILDER_FACTORY.setCoalescing(true);
+ BUILDER_FACTORY.setIgnoringElementContentWhitespace(true);
+ BUILDER_FACTORY.setIgnoringComments(true);
+ }
+
+ public enum ErrorType {
+ TRANSPORT("transport"), RPC("rpc"), PROTOCOL("protocol"), APPLICATION("application");
+
+ private final String typeValue;
+
+ ErrorType(final String typeValue) {
+ this.typeValue = Preconditions.checkNotNull(typeValue);
+ }
+
+ public String getTypeValue() {
+ return this.typeValue;
+ }
+
+ public static ErrorType from(final String text) {
+ for (ErrorType e : values()) {
+ if (e.getTypeValue().equalsIgnoreCase(text)) {
+ return e;
+ }
+ }
+
+ return APPLICATION;
+ }
+ }
+
+ public enum ErrorTag {
+ ACCESS_DENIED("access-denied"),
+ BAD_ATTRIBUTE("bad-attribute"),
+ BAD_ELEMENT("bad-element"),
+ DATA_EXISTS("data-exists"),
+ DATA_MISSING("data-missing"),
+ IN_USE("in-use"),
+ INVALID_VALUE("invalid-value"),
+ LOCK_DENIED("lock-denied"),
+ MALFORMED_MESSAGE("malformed-message"),
+ MISSING_ATTRIBUTE("missing-attribute"),
+ MISSING_ELEMENT("missing-element"),
+ OPERATION_FAILED("operation-failed"),
+ OPERATION_NOT_SUPPORTED("operation-not-supported"),
+ RESOURCE_DENIED("resource-denied"),
+ ROLLBCK_FAILED("rollback-failed"),
+ TOO_BIG("too-big"),
+ UNKNOWN_ATTRIBUTE("unknown-attribute"),
+ UNKNOWN_ELEMENT("unknown-element"),
+ UNKNOWN_NAMESPACE("unknown-namespace");
+
+ private final String tagValue;
+
+ ErrorTag(final String tagValue) {
+ this.tagValue = tagValue;
+ }
+
+ public String getTagValue() {
+ return this.tagValue;
+ }
+
+ public static ErrorTag from(final String text) {
+ for (ErrorTag e : values()) {
+ if (e.getTagValue().equals(text)) {
+ return e;
+ }
+ }
+
+ return OPERATION_FAILED;
+ }
+ }
+
+ public enum ErrorSeverity {
+ ERROR("error"), WARNING("warning");
+
+ private final String severityValue;
+
+ ErrorSeverity(final String severityValue) {
+ this.severityValue = Preconditions.checkNotNull(severityValue);
+ }
+
+ public String getSeverityValue() {
+ return this.severityValue;
+ }
+
+ public static ErrorSeverity from(final String text) {
+ for (ErrorSeverity e : values()) {
+ if (e.getSeverityValue().equalsIgnoreCase(text)) {
+ return e;
+ }
+ }
+
+ return ERROR;
+ }
+ }
+
+ private final ErrorType errorType;
+ private final ErrorTag errorTag;
+ private final ErrorSeverity errorSeverity;
+ private final Map<String, String> errorInfo;
+
+ public DocumentedException(final String message) {
+ this(message, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+
+ public DocumentedException(final String message, final Exception cause) {
+ this(message, cause, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+
+ public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message);
+ this.errorType = errorType;
+ this.errorTag = errorTag;
+ this.errorSeverity = errorSeverity;
+ this.errorInfo = errorInfo;
+ }
+
+ public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ this(message, cause, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, cause);
+ this.errorType = errorType;
+ this.errorTag = errorTag;
+ this.errorSeverity = errorSeverity;
+ this.errorInfo = errorInfo;
+ }
+
+ public static <E extends Exception> DocumentedException wrap(final E exception) throws DocumentedException {
+ final Map<String, String> errorInfo = new HashMap<>();
+ errorInfo.put(ErrorTag.OPERATION_FAILED.name(), "Exception thrown");
+ throw new DocumentedException(exception.getMessage(), exception, ErrorType.APPLICATION,
+ ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR, errorInfo);
+ }
+
+ public static DocumentedException fromXMLDocument(final Document fromDoc) {
+
+ ErrorType errorType = ErrorType.APPLICATION;
+ ErrorTag errorTag = ErrorTag.OPERATION_FAILED;
+ ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
+ Map<String, String> errorInfo = null;
+ String errorMessage = "";
+
+ Node rpcReply = fromDoc.getDocumentElement();
+
+ // FIXME: BUG? - we only handle one rpc-error.
+
+ NodeList replyChildren = rpcReply.getChildNodes();
+ for (int i = 0; i < replyChildren.getLength(); i++) {
+ Node replyChild = replyChildren.item(i);
+ if (RPC_ERROR.equals(replyChild.getNodeName())) {
+ NodeList rpcErrorChildren = replyChild.getChildNodes();
+ for (int j = 0; j < rpcErrorChildren.getLength(); j++) {
+ Node rpcErrorChild = rpcErrorChildren.item(j);
+ if (ERROR_TYPE.equals(rpcErrorChild.getNodeName())) {
+ errorType = ErrorType.from(rpcErrorChild.getTextContent());
+ } else if (ERROR_TAG.equals(rpcErrorChild.getNodeName())) {
+ errorTag = ErrorTag.from(rpcErrorChild.getTextContent());
+ } else if (ERROR_SEVERITY.equals(rpcErrorChild.getNodeName())) {
+ errorSeverity = ErrorSeverity.from(rpcErrorChild.getTextContent());
+ } else if (ERROR_MESSAGE.equals(rpcErrorChild.getNodeName())) {
+ errorMessage = rpcErrorChild.getTextContent();
+ } else if (ERROR_INFO.equals(rpcErrorChild.getNodeName())) {
+ errorInfo = parseErrorInfo(rpcErrorChild);
+ }
+ }
+
+ break;
+ }
+ }
+
+ return new DocumentedException(errorMessage, errorType, errorTag, errorSeverity, errorInfo);
+ }
+
+ private static Map<String, String> parseErrorInfo(final Node node) {
+ Map<String, String> infoMap = new HashMap<>();
+ NodeList children = node.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ infoMap.put(child.getNodeName(), child.getTextContent());
+ }
+ }
+
+ return infoMap;
+ }
+
+ public ErrorType getErrorType() {
+ return this.errorType;
+ }
+
+ public ErrorTag getErrorTag() {
+ return this.errorTag;
+ }
+
+ public ErrorSeverity getErrorSeverity() {
+ return this.errorSeverity;
+ }
+
+ public Map<String, String> getErrorInfo() {
+ return this.errorInfo;
+ }
+
+ public Document toXMLDocument() {
+ Document doc = null;
+ try {
+ doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
+
+ Node rpcReply = doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY);
+ doc.appendChild(rpcReply);
+
+ Node rpcError = doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_ERROR);
+ rpcReply.appendChild(rpcError);
+
+ rpcError.appendChild(createTextNode(doc, ERROR_TYPE, getErrorType().getTypeValue()));
+ rpcError.appendChild(createTextNode(doc, ERROR_TAG, getErrorTag().getTagValue()));
+ rpcError.appendChild(createTextNode(doc, ERROR_SEVERITY, getErrorSeverity().getSeverityValue()));
+ rpcError.appendChild(createTextNode(doc, ERROR_MESSAGE, getLocalizedMessage()));
+
+ Map<String, String> errorInfoMap = getErrorInfo();
+ if (errorInfoMap != null && !errorInfoMap.isEmpty()) {
+ /*
+ * <error-info> <bad-attribute>message-id</bad-attribute>
+ * <bad-element>rpc</bad-element> </error-info>
+ */
+
+ Node errorInfoNode = doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, ERROR_INFO);
+ errorInfoNode.setPrefix(rpcReply.getPrefix());
+ rpcError.appendChild(errorInfoNode);
+
+ for (Entry<String, String> entry : errorInfoMap.entrySet()) {
+ errorInfoNode.appendChild(createTextNode(doc, entry.getKey(), entry.getValue()));
+ }
+ }
+ } catch (final ParserConfigurationException e) {
+ // this shouldn't happen
+ LOG.error("Error outputting to XML document", e);
+ }
+
+ return doc;
+ }
+
+ private Node createTextNode(final Document doc, final String tag, final String textContent) {
+ Node node = doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, tag);
+ node.setTextContent(textContent);
+ return node;
+ }
+
+ @Override
+ public String toString() {
+ return "NetconfDocumentedException{" + "message=" + getMessage() + ", errorType=" + this.errorType
+ + ", errorTag=" + this.errorTag + ", errorSeverity=" + this.errorSeverity + ", errorInfo="
+ + this.errorInfo + '}';
+ }
+}
package org.opendaylight.netconf.api;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.w3c.dom.Document;
/**
super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
}
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
public NetconfDocumentedException(final DocumentedException exception) {
super(exception.getMessage(), (Exception) exception.getCause(), exception.getErrorType(),
exception.getErrorTag(), exception.getErrorSeverity(), exception.getErrorInfo());
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api.capability;
+
+import com.google.common.base.Optional;
+import java.util.Collection;
+import java.util.Collections;
+
+/**
+ * Capability representing a basic, one-line, string based capability.
+ */
+public class BasicCapability implements Capability {
+
+ private final String capability;
+
+ public BasicCapability(final String capability) {
+ this.capability = capability;
+ }
+
+ @Override
+ public String getCapabilityUri() {
+ return capability;
+ }
+
+ @Override
+ public Optional<String> getModuleNamespace() {
+ return Optional.absent();
+ }
+
+ @Override
+ public Optional<String> getModuleName() {
+ return Optional.absent();
+ }
+
+ @Override
+ public Optional<String> getRevision() {
+ return Optional.absent();
+ }
+
+ @Override
+ public Optional<String> getCapabilitySchema() {
+ return Optional.absent();
+ }
+
+ @Override
+ public Collection<String> getLocation() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public String toString() {
+ return capability;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api.capability;
+
+import com.google.common.base.Optional;
+import java.util.Collection;
+
+/**
+ * Contains capability URI announced by server hello message and optionally its
+ * corresponding yang schema that can be retrieved by get-schema rpc.
+ */
+public interface Capability {
+
+ String getCapabilityUri();
+
+ Optional<String> getModuleNamespace();
+
+ Optional<String> getModuleName();
+
+ Optional<String> getRevision();
+
+ Optional<String> getCapabilitySchema();
+
+ Collection<String> getLocation();
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api.capability;
+
+import com.google.common.base.Optional;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.model.api.Module;
+
+/**
+ * Yang model representing capability.
+ */
+public final class YangModuleCapability extends BasicCapability {
+
+ private final String content;
+ private final String revision;
+ private final String moduleName;
+ private final String moduleNamespace;
+
+ public YangModuleCapability(final Module module, final String moduleContent) {
+ super(toCapabilityURI(module));
+ this.content = moduleContent;
+ this.moduleName = module.getName();
+ this.moduleNamespace = module.getNamespace().toString();
+ this.revision = module.getRevision().map(Revision::toString).orElse(null);
+ }
+
+ @Override
+ public Optional<String> getCapabilitySchema() {
+ return Optional.of(content);
+ }
+
+ private static String toCapabilityURI(final Module module) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(module.getNamespace()).append("?module=").append(module.getName());
+
+ final java.util.Optional<Revision> rev = module.getRevision();
+ if (rev.isPresent()) {
+ sb.append("&revision=").append(rev.get());
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public Optional<String> getModuleName() {
+ return Optional.of(moduleName);
+ }
+
+ @Override
+ public Optional<String> getModuleNamespace() {
+ return Optional.of(moduleNamespace);
+ }
+
+ @Override
+ public Optional<String> getRevision() {
+ return Optional.of(revision);
+ }
+}
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Set;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yangtools.util.xml.UntrustedXML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
package org.opendaylight.netconf.api.monitoring;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
public interface CapabilityListener {
package org.opendaylight.netconf.api.util;
-import com.google.common.collect.Sets;
+import com.google.common.collect.ImmutableSet;
import java.util.Set;
/**
public static final String NETCONF_MONITORING = "ietf-netconf-monitoring";
public static final String NETCONF_NOTIFICATION = "ietf-netconf-notifications";
- public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
+ public static final Set<String> CONFIG_SERVICE_MARKERS = ImmutableSet.of(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
NETCONF_MONITORING, NETCONF_NOTIFICATION);
private NetconfConstants() {
--- /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.netconf.api.xml;
+
+import java.util.Collections;
+import java.util.Map;
+import org.opendaylight.netconf.api.DocumentedException;
+
+public class MissingNameSpaceException extends DocumentedException {
+ private static final long serialVersionUID = 1L;
+
+ public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity,
+ final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
+ }
+}
--- /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.netconf.api.xml;
+
+import java.util.Collections;
+import java.util.Map;
+import org.opendaylight.netconf.api.DocumentedException;
+
+public class UnexpectedElementException extends DocumentedException {
+ private static final long serialVersionUID = 1L;
+
+ public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity,
+ final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
+ }
+}
--- /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.netconf.api.xml;
+
+import java.util.Collections;
+import java.util.Map;
+import org.opendaylight.netconf.api.DocumentedException;
+
+public class UnexpectedNamespaceException extends DocumentedException {
+ private static final long serialVersionUID = 1L;
+
+ public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType,
+ final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorSeverity errorSeverity,
+ final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api.xml;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+import org.xml.sax.SAXException;
+
+public final class XmlElement {
+
+ public static final String DEFAULT_NAMESPACE_PREFIX = "";
+
+ private final Element element;
+ private static final Logger LOG = LoggerFactory.getLogger(XmlElement.class);
+
+ private XmlElement(final Element element) {
+ this.element = element;
+ }
+
+ public static XmlElement fromDomElement(final Element element) {
+ return new XmlElement(element);
+ }
+
+ public static XmlElement fromDomDocument(final Document xml) {
+ return new XmlElement(xml.getDocumentElement());
+ }
+
+ public static XmlElement fromString(final String str) throws DocumentedException {
+ try {
+ return new XmlElement(XmlUtil.readXmlToElement(str));
+ } catch (IOException | SAXException e) {
+ throw DocumentedException.wrap(e);
+ }
+ }
+
+ public static XmlElement fromDomElementWithExpected(final Element element, final String expectedName)
+ throws DocumentedException {
+ XmlElement xmlElement = XmlElement.fromDomElement(element);
+ xmlElement.checkName(expectedName);
+ return xmlElement;
+ }
+
+ public static XmlElement fromDomElementWithExpected(final Element element, final String expectedName,
+ final String expectedNamespace) throws DocumentedException {
+ XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
+ xmlElement.checkNamespace(expectedNamespace);
+ return xmlElement;
+ }
+
+ private Map<String, String> extractNamespaces() throws DocumentedException {
+ Map<String, String> namespaces = new HashMap<>();
+ NamedNodeMap attributes = element.getAttributes();
+ for (int i = 0; i < attributes.getLength(); i++) {
+ Node attribute = attributes.item(i);
+ String attribKey = attribute.getNodeName();
+ if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
+ String prefix;
+ if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
+ prefix = DEFAULT_NAMESPACE_PREFIX;
+ } else {
+ if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")) {
+ throw new DocumentedException("Attribute doesn't start with :",
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
+ }
+ namespaces.put(prefix, attribute.getNodeValue());
+ }
+ }
+
+ // namespace does not have to be defined on this element but inherited
+ if (!namespaces.containsKey(DEFAULT_NAMESPACE_PREFIX)) {
+ Optional<String> namespaceOptionally = getNamespaceOptionally();
+ if (namespaceOptionally.isPresent()) {
+ namespaces.put(DEFAULT_NAMESPACE_PREFIX, namespaceOptionally.get());
+ }
+ }
+
+ return namespaces;
+ }
+
+ public void checkName(final String expectedName) throws UnexpectedElementException {
+ if (!getName().equals(expectedName)) {
+ throw new UnexpectedElementException(String.format("Expected %s xml element but was %s", expectedName,
+ getName()),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ }
+
+ public void checkNamespaceAttribute(final String expectedNamespace)
+ throws UnexpectedNamespaceException, MissingNameSpaceException {
+ if (!getNamespaceAttribute().equals(expectedNamespace)) {
+ throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
+ getNamespaceAttribute(),
+ expectedNamespace),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ }
+
+ public void checkNamespace(final String expectedNamespace)
+ throws UnexpectedNamespaceException, MissingNameSpaceException {
+ if (!getNamespace().equals(expectedNamespace)) {
+ throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
+ getNamespace(),
+ expectedNamespace),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ }
+
+ public String getName() {
+ final String localName = element.getLocalName();
+ if (!Strings.isNullOrEmpty(localName)) {
+ return localName;
+ }
+ return element.getTagName();
+ }
+
+ public String getAttribute(final String attributeName) {
+ return element.getAttribute(attributeName);
+ }
+
+ public String getAttribute(final String attributeName, final String namespace) {
+ return element.getAttributeNS(namespace, attributeName);
+ }
+
+ public NodeList getElementsByTagName(final String name) {
+ return element.getElementsByTagName(name);
+ }
+
+ public void appendChild(final Element toAppend) {
+ this.element.appendChild(toAppend);
+ }
+
+ public Element getDomElement() {
+ return element;
+ }
+
+ public Map<String, Attr> getAttributes() {
+
+ Map<String, Attr> mappedAttributes = Maps.newHashMap();
+
+ NamedNodeMap attributes = element.getAttributes();
+ for (int i = 0; i < attributes.getLength(); i++) {
+ Attr attr = (Attr) attributes.item(i);
+ mappedAttributes.put(attr.getNodeName(), attr);
+ }
+
+ return mappedAttributes;
+ }
+
+ /**
+ * Non recursive.
+ */
+ private List<XmlElement> getChildElementsInternal(final ElementFilteringStrategy strat) {
+ NodeList childNodes = element.getChildNodes();
+ final List<XmlElement> result = new ArrayList<>();
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ Node item = childNodes.item(i);
+ if (!(item instanceof Element)) {
+ continue;
+ }
+ if (strat.accept((Element) item)) {
+ result.add(new XmlElement((Element) item));
+ }
+ }
+
+ return result;
+ }
+
+ public List<XmlElement> getChildElements() {
+ return getChildElementsInternal(e -> true);
+ }
+
+ /**
+ * Returns the child elements for the given tag.
+ *
+ * @param tagName tag name without prefix
+ * @return List of child elements
+ */
+ public List<XmlElement> getChildElements(final String tagName) {
+ return getChildElementsInternal(e -> {
+ // localName returns pure localName without prefix
+ return e.getLocalName().equals(tagName);
+ });
+ }
+
+ public List<XmlElement> getChildElementsWithinNamespace(final String childName, final String namespace) {
+ return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
+ xmlElement -> xmlElement.getName().equals(childName)));
+ }
+
+ public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
+ return getChildElementsInternal(e -> {
+ try {
+ return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
+ } catch (final MissingNameSpaceException e1) {
+ return false;
+ }
+ });
+ }
+
+ public Optional<XmlElement> getOnlyChildElementOptionally(final String childName) {
+ List<XmlElement> nameElements = getChildElements(childName);
+ if (nameElements.size() != 1) {
+ return Optional.absent();
+ }
+ return Optional.of(nameElements.get(0));
+ }
+
+ public Optional<XmlElement> getOnlyChildElementOptionally(final String childName, final String namespace) {
+ List<XmlElement> children = getChildElementsWithinNamespace(namespace);
+ children = Lists.newArrayList(Collections2.filter(children,
+ xmlElement -> xmlElement.getName().equals(childName)));
+ if (children.size() != 1) {
+ return Optional.absent();
+ }
+ return Optional.of(children.get(0));
+ }
+
+ public Optional<XmlElement> getOnlyChildElementOptionally() {
+ List<XmlElement> children = getChildElements();
+ if (children.size() != 1) {
+ return Optional.absent();
+ }
+ return Optional.of(children.get(0));
+ }
+
+ public XmlElement getOnlyChildElementWithSameNamespace(final String childName) throws DocumentedException {
+ return getOnlyChildElement(childName, getNamespace());
+ }
+
+ public XmlElement getOnlyChildElementWithSameNamespace() throws DocumentedException {
+ XmlElement childElement = getOnlyChildElement();
+ childElement.checkNamespace(getNamespace());
+ return childElement;
+ }
+
+ public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(final String childName) {
+ Optional<String> namespace = getNamespaceOptionally();
+ if (namespace.isPresent()) {
+ List<XmlElement> children = getChildElementsWithinNamespace(namespace.get());
+ children = Lists.newArrayList(Collections2.filter(children,
+ xmlElement -> xmlElement.getName().equals(childName)));
+ if (children.size() != 1) {
+ return Optional.absent();
+ }
+ return Optional.of(children.get(0));
+ }
+ return Optional.absent();
+ }
+
+ public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
+ Optional<XmlElement> child = getOnlyChildElementOptionally();
+ if (child.isPresent()
+ && child.get().getNamespaceOptionally().isPresent()
+ && getNamespaceOptionally().isPresent()
+ && getNamespaceOptionally().get().equals(child.get().getNamespaceOptionally().get())) {
+ return child;
+ }
+ return Optional.absent();
+ }
+
+ public XmlElement getOnlyChildElement(final String childName, final String namespace) throws DocumentedException {
+ List<XmlElement> children = getChildElementsWithinNamespace(namespace);
+ children = Lists.newArrayList(Collections2.filter(children,
+ xmlElement -> xmlElement.getName().equals(childName)));
+ if (children.size() != 1) {
+ throw new DocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
+ childName, toString(), children.size()),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+
+ return children.get(0);
+ }
+
+ public XmlElement getOnlyChildElement(final String childName) throws DocumentedException {
+ List<XmlElement> nameElements = getChildElements(childName);
+ if (nameElements.size() != 1) {
+ throw new DocumentedException("One element " + childName + " expected in " + toString(),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ return nameElements.get(0);
+ }
+
+ public XmlElement getOnlyChildElement() throws DocumentedException {
+ List<XmlElement> children = getChildElements();
+ if (children.size() != 1) {
+ throw new DocumentedException(String.format("One element expected in %s but was %s", toString(),
+ children.size()),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ return children.get(0);
+ }
+
+ public String getTextContent() throws DocumentedException {
+ NodeList childNodes = element.getChildNodes();
+ if (childNodes.getLength() == 0) {
+ return DEFAULT_NAMESPACE_PREFIX;
+ }
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ Node textChild = childNodes.item(i);
+ if (textChild instanceof Text) {
+ String content = textChild.getTextContent();
+ return content.trim();
+ }
+ }
+ throw new DocumentedException(getName() + " should contain text.",
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR
+ );
+ }
+
+ public Optional<String> getOnlyTextContentOptionally() {
+ // only return text content if this node has exactly one Text child node
+ if (element.getChildNodes().getLength() == 1) {
+ Node item = element.getChildNodes().item(0);
+ if (item instanceof Text) {
+ return Optional.of(((Text) item).getWholeText());
+ }
+ }
+ return Optional.absent();
+ }
+
+ public String getNamespaceAttribute() throws MissingNameSpaceException {
+ String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
+ if (attribute.isEmpty() || attribute.equals(DEFAULT_NAMESPACE_PREFIX)) {
+ throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
+ toString()),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ return attribute;
+ }
+
+ public Optional<String> getNamespaceAttributeOptionally() {
+ String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
+ if (attribute.isEmpty() || attribute.equals(DEFAULT_NAMESPACE_PREFIX)) {
+ return Optional.absent();
+ }
+ return Optional.of(attribute);
+ }
+
+ public Optional<String> getNamespaceOptionally() {
+ String namespaceURI = element.getNamespaceURI();
+ if (Strings.isNullOrEmpty(namespaceURI)) {
+ return Optional.absent();
+ } else {
+ return Optional.of(namespaceURI);
+ }
+ }
+
+ public String getNamespace() throws MissingNameSpaceException {
+ Optional<String> namespaceURI = getNamespaceOptionally();
+ if (!namespaceURI.isPresent()) {
+ throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.OPERATION_FAILED,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ return namespaceURI.get();
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("XmlElement{");
+ sb.append("name='").append(getName()).append('\'');
+ if (element.getNamespaceURI() != null) {
+ try {
+ sb.append(", namespace='").append(getNamespace()).append('\'');
+ } catch (final MissingNameSpaceException e) {
+ LOG.trace("Missing namespace for element.");
+ }
+ }
+ sb.append('}');
+ return sb.toString();
+ }
+
+ /**
+ * Search for element's attributes defining namespaces. Look for the one
+ * namespace that matches prefix of element's text content. E.g.
+ *
+ * <pre>
+ * <type
+ * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">
+ * th-java:threadfactory-naming</type>
+ * </pre>
+ *
+ * <p>
+ * returns {"th-java","urn:.."}. If no prefix is matched, then default
+ * namespace is returned with empty string as key. If no default namespace
+ * is found value will be null.
+ */
+ public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent()
+ throws DocumentedException {
+ Map<String, String> namespaces = extractNamespaces();
+ String textContent = getTextContent();
+ int indexOfColon = textContent.indexOf(':');
+ String prefix;
+ if (indexOfColon > -1) {
+ prefix = textContent.substring(0, indexOfColon);
+ } else {
+ prefix = DEFAULT_NAMESPACE_PREFIX;
+ }
+ if (!namespaces.containsKey(prefix)) {
+ throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element)
+ + ". Prefix from content is " + prefix + ". Found namespaces " + namespaces);
+ }
+ return Maps.immutableEntry(prefix, namespaces.get(prefix));
+ }
+
+ public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
+ List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
+ return Lists.newArrayList(Collections2.filter(children, xmlElement -> xmlElement.getName().equals(childName)));
+ }
+
+ public void checkUnrecognisedElements(final List<XmlElement> recognisedElements,
+ final XmlElement... additionalRecognisedElements) throws DocumentedException {
+ List<XmlElement> childElements = getChildElements();
+ childElements.removeAll(recognisedElements);
+ for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
+ childElements.remove(additionalRecognisedElement);
+ }
+ if (!childElements.isEmpty()) {
+ throw new DocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR);
+ }
+ }
+
+ public void checkUnrecognisedElements(final XmlElement... additionalRecognisedElements) throws DocumentedException {
+ checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+
+ XmlElement that = (XmlElement) obj;
+
+ return element.isEqualNode(that.element);
+
+ }
+
+ @Override
+ public int hashCode() {
+ return element.hashCode();
+ }
+
+ public boolean hasNamespace() {
+ return getNamespaceAttributeOptionally().isPresent() || getNamespaceOptionally().isPresent();
+ }
+
+ private interface ElementFilteringStrategy {
+ boolean accept(Element element);
+ }
+}
*/
package org.opendaylight.netconf.api.xml;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-
public final class XmlNetconfConstants {
private XmlNetconfConstants() {}
public static final String RPC_KEY = "rpc";
public static final String NOTIFICATION_ELEMENT_NAME = "notification";
public static final String EVENT_TIME = "eventTime";
+ public static final String PREFIX = "prefix";
public static final String MESSAGE_ID = "message-id";
public static final String SESSION_ID = "session-id";
public static final String GET = "get";
public static final String GET_CONFIG = "get-config";
- public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 =
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+ public static final String RPC_REPLY_KEY = "rpc-reply";
+
+ public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0";
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_0 = "urn:ietf:params:netconf:base:1.0";
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_1 = "urn:ietf:params:netconf:base:1.1";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0 = "urn:ietf:params:xml:ns:netconf:exi:1.0";
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.api.xml;
+
+import com.google.common.base.Optional;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
+
+public final class XmlUtil {
+
+ public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
+ public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
+ private static final DocumentBuilderFactory BUILDER_FACTORY;
+ private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
+ private static final SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+
+ static {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ try {
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
+ // Performance improvement for messages with size <10k according to
+ // https://xerces.apache.org/xerces2-j/faq-performance.html
+ factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
+ } catch (final ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ factory.setNamespaceAware(true);
+ factory.setCoalescing(true);
+ factory.setIgnoringElementContentWhitespace(true);
+ factory.setIgnoringComments(true);
+ BUILDER_FACTORY = factory;
+ }
+
+ private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>() {
+ @Override
+ protected DocumentBuilder initialValue() {
+ try {
+ return BUILDER_FACTORY.newDocumentBuilder();
+ } catch (final ParserConfigurationException e) {
+ throw new IllegalStateException("Failed to create threadLocal dom builder", e);
+ }
+ }
+
+ @Override
+ public void set(final DocumentBuilder value) {
+ throw new UnsupportedOperationException();
+ }
+ };
+
+ private XmlUtil() {
+ throw new UnsupportedOperationException("Utility class");
+ }
+
+ public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
+ return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
+ }
+
+ public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
+ Document doc = readXmlToDocument(xmlContent);
+ return doc.getDocumentElement();
+ }
+
+ public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
+ Document doc = readXmlToDocument(xmlContent);
+ return doc.getDocumentElement();
+ }
+
+ public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
+ return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
+ }
+
+ // TODO improve exceptions throwing
+ // along with XmlElement
+
+ public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
+ Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
+
+ doc.getDocumentElement().normalize();
+ return doc;
+ }
+
+ public static Document newDocument() {
+ return DEFAULT_DOM_BUILDER.get().newDocument();
+ }
+
+ public static Element createElement(final Document document, final String qmame,
+ final Optional<String> namespaceURI) {
+ if (namespaceURI.isPresent()) {
+ final Element element = document.createElementNS(namespaceURI.get(), qmame);
+ String name = XMLNS_ATTRIBUTE_KEY;
+ if (element.getPrefix() != null) {
+ name += ":" + element.getPrefix();
+ }
+ element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
+ return element;
+ }
+ return document.createElement(qmame);
+ }
+
+ public static Element createTextElement(final Document document, final String qname, final String content,
+ final Optional<String> namespaceURI) {
+ Element typeElement = createElement(document, qname, namespaceURI);
+ typeElement.appendChild(document.createTextNode(content));
+ return typeElement;
+ }
+
+ public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
+ final String prefix, final String namespace, final String contentWithoutPrefix) {
+
+ return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
+ Optional.<String>absent());
+ }
+
+ public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
+ final String prefix, final String namespace, final String contentWithoutPrefix,
+ final Optional<String> namespaceURI) {
+
+ String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
+ Element element = createTextElement(document, qname, content, namespaceURI);
+ String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
+ element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
+ return element;
+ }
+
+ public static String createPrefixedValue(final String prefix, final String value) {
+ return prefix + ":" + value;
+ }
+
+ public static String toString(final Document document) {
+ return toString(document.getDocumentElement());
+ }
+
+ public static String toString(final Element xml) {
+ return toString(xml, false);
+ }
+
+ public static String toString(final XmlElement xmlElement) {
+ return toString(xmlElement.getDomElement(), false);
+ }
+
+ public static String toString(final Element xml, final boolean addXmlDeclaration) {
+ try {
+ Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
+
+ StreamResult result = new StreamResult(new StringWriter());
+ DOMSource source = new DOMSource(xml);
+ transformer.transform(source, result);
+
+ return result.getWriter().toString();
+ } catch (TransformerFactoryConfigurationError | TransformerException e) {
+ throw new IllegalStateException("Unable to serialize xml element " + xml, e);
+ }
+ }
+
+ public static String toString(final Document doc, final boolean addXmlDeclaration) {
+ return toString(doc.getDocumentElement(), addXmlDeclaration);
+ }
+
+ public static Schema loadSchema(final InputStream... fromStreams) {
+ Source[] sources = new Source[fromStreams.length];
+ int index = 0;
+ for (InputStream stream : fromStreams) {
+ sources[index++] = new StreamSource(stream);
+ }
+
+ try {
+ return SCHEMA_FACTORY.newSchema(sources);
+ } catch (final SAXException e) {
+ throw new IllegalStateException("Failed to instantiate XML schema", e);
+ }
+ }
+
+ public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
+ try {
+ return expr.evaluate(rootNode, returnType);
+ } catch (final XPathExpressionException e) {
+ throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
+ }
+ }
+
+ public static Document createDocumentCopy(final Document original) {
+ final Document copiedDocument = newDocument();
+ final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
+ copiedDocument.appendChild(copiedRoot);
+ return copiedDocument;
+ }
+}
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
--- /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.netconf.api.xml;
+
+import static org.hamcrest.CoreMatchers.both;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.google.common.base.Optional;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+public class XmlElementTest {
+
+ private final String elementAsString =
+ "<top xmlns=\"namespace\" xmlns:a=\"attrNamespace\" a:attr1=\"value1\" attr2=\"value2\">"
+ + "<inner>" + "<deepInner>deepValue</deepInner>" + "</inner>"
+ + "<innerNamespace xmlns=\"innerNamespace\">innerNamespaceValue</innerNamespace>"
+ + "<innerPrefixed xmlns:b=\"prefixedValueNamespace\">b:valueWithPrefix</innerPrefixed>" + "</top>";
+ private Document document;
+ private Element element;
+ private XmlElement xmlElement;
+
+ @Before
+ public void setUp() throws Exception {
+ document = XmlUtil.readXmlToDocument(elementAsString);
+ element = document.getDocumentElement();
+ xmlElement = XmlElement.fromDomElement(element);
+ }
+
+ @Test
+ public void testConstruct() throws Exception {
+ final XmlElement fromString = XmlElement.fromString(elementAsString);
+ assertEquals(fromString, xmlElement);
+ XmlElement.fromDomDocument(document);
+ XmlElement.fromDomElement(element);
+ XmlElement.fromDomElementWithExpected(element, "top");
+ XmlElement.fromDomElementWithExpected(element, "top", "namespace");
+
+ try {
+ XmlElement.fromString("notXml");
+ fail();
+ } catch (final DocumentedException e) {
+ // expected
+ }
+
+ try {
+ XmlElement.fromDomElementWithExpected(element, "notTop");
+ fail();
+ } catch (final DocumentedException e) {
+ // expected
+ }
+
+ try {
+ XmlElement.fromDomElementWithExpected(element, "top", "notNamespace");
+ fail();
+ } catch (final DocumentedException e) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testGetters() throws Exception {
+ assertEquals(element, xmlElement.getDomElement());
+ assertEquals(element.getElementsByTagName("inner").getLength(),
+ xmlElement.getElementsByTagName("inner").getLength());
+
+ assertEquals("top", xmlElement.getName());
+ assertTrue(xmlElement.hasNamespace());
+ assertEquals("namespace", xmlElement.getNamespace());
+ assertEquals("namespace", xmlElement.getNamespaceAttribute());
+ assertEquals(Optional.of("namespace"), xmlElement.getNamespaceOptionally());
+
+ assertEquals("value1", xmlElement.getAttribute("attr1", "attrNamespace"));
+ assertEquals("value2", xmlElement.getAttribute("attr2"));
+ assertEquals(2 + 2/*Namespace definition*/, xmlElement.getAttributes().size());
+
+ assertEquals(3, xmlElement.getChildElements().size());
+ assertEquals(1, xmlElement.getChildElements("inner").size());
+ assertTrue(xmlElement.getOnlyChildElementOptionally("inner").isPresent());
+ assertTrue(xmlElement.getOnlyChildElementWithSameNamespaceOptionally("inner").isPresent());
+ assertEquals(0, xmlElement.getChildElements("unknown").size());
+ assertFalse(xmlElement.getOnlyChildElementOptionally("unknown").isPresent());
+ assertEquals(1, xmlElement.getChildElementsWithSameNamespace("inner").size());
+ assertEquals(0, xmlElement.getChildElementsWithSameNamespace("innerNamespace").size());
+ assertEquals(1, xmlElement.getChildElementsWithinNamespace("innerNamespace", "innerNamespace").size());
+ assertTrue(xmlElement.getOnlyChildElementOptionally("innerNamespace", "innerNamespace").isPresent());
+ assertFalse(xmlElement.getOnlyChildElementOptionally("innerNamespace", "unknownNamespace").isPresent());
+
+ final XmlElement noNamespaceElement = XmlElement.fromString("<noNamespace/>");
+ assertFalse(noNamespaceElement.hasNamespace());
+ try {
+ noNamespaceElement.getNamespace();
+ fail();
+ } catch (final MissingNameSpaceException e) {
+ // expected
+ }
+
+ final XmlElement inner = xmlElement.getOnlyChildElement("inner");
+ final XmlElement deepInner = inner.getOnlyChildElementWithSameNamespaceOptionally().get();
+ assertEquals(deepInner, inner.getOnlyChildElementWithSameNamespace());
+ assertEquals(Optional.<XmlElement>absent(), xmlElement.getOnlyChildElementOptionally("unknown"));
+ assertEquals("deepValue", deepInner.getTextContent());
+ assertEquals("deepValue", deepInner.getOnlyTextContentOptionally().get());
+ assertEquals("deepValue", deepInner.getOnlyTextContentOptionally().get());
+ }
+
+ @Test
+ public void testExtractNamespaces() throws Exception {
+ final XmlElement innerPrefixed = xmlElement.getOnlyChildElement("innerPrefixed");
+ Map.Entry<String, String> namespaceOfTextContent = innerPrefixed.findNamespaceOfTextContent();
+
+ assertNotNull(namespaceOfTextContent);
+ assertEquals("b", namespaceOfTextContent.getKey());
+ assertEquals("prefixedValueNamespace", namespaceOfTextContent.getValue());
+ final XmlElement innerNamespace = xmlElement.getOnlyChildElement("innerNamespace");
+ namespaceOfTextContent = innerNamespace.findNamespaceOfTextContent();
+
+ assertEquals("", namespaceOfTextContent.getKey());
+ assertEquals("innerNamespace", namespaceOfTextContent.getValue());
+ }
+
+ @Test
+ public void testUnrecognisedElements() throws Exception {
+ xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"),
+ xmlElement.getOnlyChildElement("innerPrefixed"), xmlElement.getOnlyChildElement("innerNamespace"));
+
+ try {
+ xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"));
+ fail();
+ } catch (final DocumentedException e) {
+ assertThat(e.getMessage(), both(containsString("innerNamespace")).and(containsString("innerNamespace")));
+ }
+ }
+}
--- /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.netconf.api.xml;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.google.common.base.Optional;
+import java.io.ByteArrayInputStream;
+import org.custommonkey.xmlunit.Diff;
+import org.custommonkey.xmlunit.XMLUnit;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXParseException;
+
+public class XmlUtilTest {
+
+ private final String xml = "<top xmlns=\"namespace\">\n" + "<innerText>value</innerText>\n"
+ + "<innerPrefixedText xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n"
+ + "<innerPrefixedText xmlns=\"randomNamespace\" xmlns:pref=\"prefixNamespace\">prefix:value"
+ + "</innerPrefixedText>\n"
+ + "</top>";
+
+ @Test
+ public void testCreateElement() throws Exception {
+ final Document document = XmlUtil.newDocument();
+ final Element top = XmlUtil.createElement(document, "top", Optional.of("namespace"));
+
+ top.appendChild(XmlUtil.createTextElement(document, "innerText", "value", Optional.of("namespace")));
+ top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref",
+ "prefixNamespace", "value", Optional.of("namespace")));
+ top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref",
+ "prefixNamespace", "value", Optional.of("randomNamespace")));
+
+ document.appendChild(top);
+ assertEquals("top", XmlUtil.createDocumentCopy(document).getDocumentElement().getTagName());
+
+ XMLUnit.setIgnoreAttributeOrder(true);
+ XMLUnit.setIgnoreWhitespace(true);
+
+ final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(xml), document);
+ assertTrue(diff.toString(), diff.similar());
+ }
+
+ @Test
+ public void testLoadSchema() throws Exception {
+ XmlUtil.loadSchema();
+ try {
+ XmlUtil.loadSchema(new ByteArrayInputStream(xml.getBytes()));
+ fail("Input stream does not contain xsd");
+ } catch (final IllegalStateException e) {
+ assertTrue(e.getCause() instanceof SAXParseException);
+ }
+
+ }
+
+ @Test(expected = SAXParseException.class)
+ public void testXXEFlaw() throws Exception {
+ XmlUtil.readXmlToDocument(
+ "<!DOCTYPE foo [ \n" + "<!ELEMENT foo ANY >\n" + "<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>\n"
+ + "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + " <capabilities>\n"
+ + " <capability>urn:ietf:params:netconf:base:1.0 &xxe;</capability>\n"
+ + " </capabilities>\n" + " </hello>]]>]]>");
+ }
+
+}
<artifactId>aaa-authn-odl-plugin</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netconf-connector</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-api</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netconf-connector</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-all</artifactId>
<version>1.5.0-SNAPSHOT</version>
<name>${project.artifactId}</name>
<packaging>bundle</packaging>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
import io.netty.channel.EventLoopGroup;
import io.netty.util.Timer;
import io.netty.util.concurrent.Future;
-import java.io.Closeable;
import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.protocol.framework.AbstractDispatcher;
import org.slf4j.LoggerFactory;
public class NetconfClientDispatcherImpl extends AbstractDispatcher<NetconfClientSession, NetconfClientSessionListener>
- implements NetconfClientDispatcher, Closeable {
+ implements NetconfClientDispatcher {
private static final Logger LOG = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class);
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.util.Set;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfClientSessionPreferences;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
if (!ifNegotiatedAlready()) {
LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
// If exi should be used, try to initiate exi communication
// Call negotiationSuccessFul after exi negotiation is finished successfully or not
- if (shouldUseExi(netconfMessage)) {
+ final NetconfMessage startExiMessage = sessionPreferences.getStartExiMessage();
+ if (shouldUseExi(netconfMessage) && startExiMessage instanceof NetconfStartExiMessage) {
LOG.debug("Netconf session {} should use exi.", session);
- NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
- tryToInitiateExi(session, startExiMessage);
+ tryToInitiateExi(session, (NetconfStartExiMessage) startExiMessage);
} else {
// Exi is not supported, release session immediately
LOG.debug("Netconf session {} isn't capable of using exi.", session);
});
}
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
return containsExi10Capability(helloMsg.getDocument())
&& containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
}
}
- return Long.valueOf(textContent);
+ return Long.parseLong(textContent);
}
private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
package org.opendaylight.netconf.client;
import com.google.common.base.Preconditions;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
private NetconfClientSession clientSession;
@GuardedBy("this")
+ @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED")
private void dispatchRequest() {
while (!requests.isEmpty()) {
final RequestEntry e = requests.peek();
negotiationFutureListener = future -> {
if (future.isSuccess()) {
- connectPromise.setSuccess();
+ channelPromise.setSuccess();
}
};
//complete connection promise with netconf negotiation future
negotiationFuture.addListener(negotiationFutureListener);
} else {
- connectPromise.setFailure(future.cause());
+ channelPromise.setFailure(future.cause());
}
});
ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
@Override
public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
+ if (connectPromise == null) {
+ return;
+ }
+
// If we have already succeeded and the session was dropped after, we need to fire inactive to notify
// reconnect logic
if (connectPromise.isSuccess()) {
return sslHandlerFactory;
}
- @SuppressWarnings("checkstyle:FallThrough")
private void validateConfiguration() {
Preconditions.checkNotNull(clientProtocol, " ");
switch (clientProtocol) {
case TLS:
+ validateTlsConfiguration();
+ validateTcpConfiguration();
+ break;
case SSH:
- if (clientProtocol == NetconfClientProtocol.SSH) {
- validateSshConfiguration();
- } else {
- validateTlsConfiguration();
- }
- // Fall through intentional (ssh or tls validation is a superset of tcp validation)
+ validateSshConfiguration();
+ validateTcpConfiguration();
+ break;
case TCP:
validateTcpConfiguration();
break;
public enum NetconfClientProtocol {
TCP, SSH, TLS
}
-}
\ No newline at end of file
+}
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelProgressivePromise;
+import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.HashedWheelTimer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfClientSessionPreferences;
+import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
-import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
private NetconfHelloMessage helloMessage;
private ChannelPipeline pipeline;
- private ChannelFuture future;
+ private ChannelPromise future;
private Channel channel;
private ChannelInboundHandlerAdapter channelInboundHandlerAdapter;
@Before
public void setUp() throws Exception {
- helloMessage = NetconfHelloMessage.createClientHello(Sets.newSet("exi:1.0"), Optional
- .<NetconfHelloMessageAdditionalHeader>absent());
+ helloMessage = NetconfHelloMessage.createClientHello(Sets.newSet("exi:1.0"), Optional.absent());
pipeline = mockChannelPipeline();
future = mockChannelFuture();
channel = mockChannel();
Channel ret = mock(Channel.class);
ChannelHandler channelHandler = mockChannelHandler();
doReturn("").when(ret).toString();
+ doReturn(future).when(ret).newPromise();
doReturn(future).when(ret).close();
doReturn(future).when(ret).writeAndFlush(anyObject());
+ doReturn(future).when(ret).writeAndFlush(anyObject(), anyObject());
doReturn(true).when(ret).isOpen();
doReturn(pipeline).when(ret).pipeline();
doReturn("").when(pipeline).toString();
return ret;
}
- private static ChannelFuture mockChannelFuture() {
- ChannelFuture future = mock(ChannelFuture.class);
+ private static ChannelPromise mockChannelFuture() {
+ ChannelPromise future = mock(ChannelPromise.class);
doReturn(future).when(future).addListener(any(GenericFutureListener.class));
return future;
}
private void mockEventLoop() {
final EventLoop eventLoop = mock(EventLoop.class);
doReturn(eventLoop).when(channel).eventLoop();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- final Runnable runnable = (Runnable) args[0];
- runnable.run();
- return null;
- }
+ doAnswer(invocation -> {
+ invocation.getArgumentAt(0, Runnable.class).run();
+ return null;
}).when(eventLoop).execute(any(Runnable.class));
}
return new NetconfClientSessionNegotiator(preferences, promise, channel, timer, sessionListener, timeout);
}
- private NetconfHelloMessage createHelloMsg(final String name) throws Exception {
+ private static NetconfHelloMessage createHelloMsg(final String name) throws Exception {
final InputStream stream = NetconfClientSessionNegotiatorTest.class.getResourceAsStream(name);
final Document doc = XmlUtil.readXmlToDocument(stream);
return new NetconfHelloMessage(doc);
}
- private Set<String> createCapabilities(String name) throws Exception {
+ private static Set<String> createCapabilities(final String name) throws Exception {
NetconfHelloMessage hello = createHelloMsg(name);
return ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(hello.getDocument()));
}
@Test
- public void testNetconfClientSessionNegotiator() throws Exception {
+ public void testNetconfClientSessionNegotiator() throws NetconfDocumentedException {
Promise<NetconfClientSession> promise = mock(Promise.class);
doReturn(promise).when(promise).setSuccess(anyObject());
NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, null);
Set<String> caps = Sets.newSet("exi:1.0");
NetconfHelloMessage message = NetconfHelloMessage.createServerHello(caps, 10);
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
- channelInboundHandlerAdapter = ((ChannelInboundHandlerAdapter) invocationOnMock.getArguments()[2]);
- return null;
- }
+ doAnswer(invocationOnMock -> {
+ channelInboundHandlerAdapter = (ChannelInboundHandlerAdapter) invocationOnMock.getArguments()[2];
+ return null;
}).when(pipeline).addAfter(anyString(), anyString(), any(ChannelHandler.class));
ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class);
import static org.mockito.Mockito.verify;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
+import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
public class SimpleNetconfClientSessionListenerTest {
private Channel channel;
- private ChannelFuture channelFuture;
+ private ChannelPromise channelFuture;
Set<String> caps;
private NetconfHelloMessage helloMessage;
private NetconfMessage message;
private NetconfClientSession clientSession;
@Before
- public void setUp() throws Exception {
+ public void setUp() throws NetconfDocumentedException {
channel = mock(Channel.class);
- channelFuture = mock(ChannelFuture.class);
+ channelFuture = mock(ChannelPromise.class);
mockEventLoop();
+ doReturn(channelFuture).when(channel).newPromise();
doReturn(channelFuture).when(channel).writeAndFlush(anyObject());
+ doReturn(channelFuture).when(channel).writeAndFlush(anyObject(), any(ChannelPromise.class));
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
caps = Sets.newSet("a", "b");
helloMessage = NetconfHelloMessage.createServerHello(caps, 10);
private void mockEventLoop() {
final EventLoop eventLoop = mock(EventLoop.class);
doReturn(eventLoop).when(channel).eventLoop();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- final Runnable runnable = (Runnable) args[0];
- runnable.run();
- return null;
- }
+ doAnswer(invocation -> {
+ invocation.getArgumentAt(0, Runnable.class).run();
+ return null;
}).when(eventLoop).execute(any(Runnable.class));
}
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject());
+ verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
simpleListener.onSessionDown(clientSession, new Exception());
assertFalse(promise.isSuccess());
}
@Test
- public void testSendRequest() throws Exception {
+ public void testSendRequest() {
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject());
+ verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
simpleListener.sendRequest(message);
assertFalse(promise.isSuccess());
}
@Test
- public void testOnMessage() throws Exception {
+ public void testOnMessage() {
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject());
+ verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
simpleListener.onMessage(clientSession, message);
assertTrue(promise.isSuccess());
<scope>test</scope>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
package org.opendaylight.netconf.console.commands;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Strings;
+
+import java.util.Arrays;
+
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.console.AbstractAction;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.Protocol.Name;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.ProtocolBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.protocol.specification.TlsCase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.protocol.specification.TlsCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.protocol.specification.tls._case.TlsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder;
@Option(name = "-U",
aliases = { "--username" },
description = "Username for netconf connection",
- required = true,
+ required = false,
multiValued = false)
private String username;
@Option(name = "-P",
aliases = { "--password" },
description = "Password for netconf connection",
- required = true,
+ required = false,
multiValued = false)
private String password;
multiValued = false)
private String connectionType = "false";
+ @Option(name = "-pr",
+ aliases = { "--protocol" },
+ description = "Which protocol to be used, ssh or tls",
+ required = false,
+ multiValued = false)
+ private String protocol = "ssh";
+
+ @Option(name = "-ev",
+ aliases = { "--excluded-versions" },
+ description = "TLS versions not supported by target device",
+ required = false,
+ multiValued = false)
+ private String excludedTlsVersions;
+
@Option(name = "-sl",
aliases = { "--schemaless" },
description = "Schemaless surpport, true for schemaless",
final boolean isTcpOnly = connectionType.equals("true");
final boolean isSchemaless = schemaless.equals("true");
- final Credentials credentials =
- new LoginPasswordBuilder().setPassword(password).setUsername(username).build();
-
- final NetconfNode netconfNode = new NetconfNodeBuilder()
- .setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
- .setPort(new PortNumber(Integer.decode(devicePort)))
- .setTcpOnly(isTcpOnly)
- .setSchemaless(isSchemaless)
- .setCredentials(credentials)
- .build();
-
- service.connectDevice(netconfNode, deviceId);
+
+ final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
+ netconfNodeBuilder.setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
+ .setPort(new PortNumber(Integer.decode(devicePort)))
+ .setTcpOnly(isTcpOnly)
+ .setSchemaless(isSchemaless);
+
+ if (isTcpOnly || protocol.equalsIgnoreCase("ssh")) {
+ if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
+ return "Empty Username:" + username + " or Password:" + password
+ + ". In TCP or SSH mode, you must provide valid username and password.";
+ }
+ final Credentials credentials =
+ new LoginPasswordBuilder().setPassword(password).setUsername(username).build();
+ netconfNodeBuilder.setCredentials(credentials);
+ if (!isTcpOnly) {
+ netconfNodeBuilder.setProtocol(new ProtocolBuilder().setName(Name.SSH).build());
+ }
+ } else if (protocol.equalsIgnoreCase("tls")) {
+ TlsCase tlsCase = null;
+ if (!Strings.isNullOrEmpty(excludedTlsVersions)) {
+ tlsCase = new TlsCaseBuilder()
+ .setTls(new TlsBuilder()
+ .setExcludedVersions(Arrays.asList(excludedTlsVersions.split(","))).build())
+ .build();
+ }
+ netconfNodeBuilder.setProtocol(new ProtocolBuilder()
+ .setName(Name.TLS)
+ .setSpecification(tlsCase)
+ .build());
+ } else {
+ return "Invalid protocol: " + protocol + ". Only SSH and TLS are supported.";
+ }
+
+ service.connectDevice(netconfNodeBuilder.build(), deviceId);
final String message = "Netconf connector added succesfully";
return message;
}
table.column(NetconfConsoleConstants.NETCONF_PORT).alignLeft();
table.column(NetconfConsoleConstants.STATUS).alignLeft();
- for (final String nodeIds : allDevices.keySet()) {
- final Map<String, String> attributes = allDevices.get(nodeIds);
+ for (final Map<String, String> attributes : allDevices.values()) {
table.addRow().addContent(attributes.get(NetconfConsoleConstants.NETCONF_ID),
attributes.get(NetconfConsoleConstants.NETCONF_IP),
attributes.get(NetconfConsoleConstants.NETCONF_PORT),
import com.google.common.base.Strings;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import javax.annotation.Nonnull;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
}
if (!NetconfCommandUtils.isIpValid(deviceIp)
- || (devicePort != null && !NetconfCommandUtils.isPortValid(devicePort))) {
+ || devicePort != null && !NetconfCommandUtils.isPortValid(devicePort)) {
return "Invalid IP:" + deviceIp + " or Port:" + devicePort + "Please enter a valid entry to proceed.";
}
table.column(NetconfConsoleConstants.STATUS).alignLeft();
table.column(NetconfConsoleConstants.AVAILABLE_CAPABILITIES).alignLeft();
- for (final String nodeId : devices.keySet()) {
- final Map<String, List<String>> device = devices.get(nodeId);
+ for (final Entry<String, Map<String, List<String>>> entry : devices.entrySet()) {
+ final String nodeId = entry.getKey();
+ final Map<String, List<String>> device = entry.getValue();
table.addRow().addContent(nodeId,
device.get(NetconfConsoleConstants.NETCONF_IP).get(NetconfConsoleConstants.DEFAULT_INDEX),
device.get(NetconfConsoleConstants.NETCONF_PORT).get(NetconfConsoleConstants.DEFAULT_INDEX),
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
attributes.put(NetconfConsoleConstants.NETCONF_IP,
netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
- attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
+ attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name()
+ .toLowerCase(Locale.ROOT));
netconfNodes.put(node.getNodeId().getValue(), attributes);
}
return netconfNodes;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
+import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
+import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.opendaylight.netconf.console.api.NetconfCommands;
import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(Strings.class)
public class NetconfCommandsImplCallsTest {
@Mock
netconfConnectDeviceCommand = new NetconfConnectDeviceCommand(netconfCommands, "192.168.1.1", "7777");
+ PowerMockito.mockStatic(Strings.class);
+ given(Strings.isNullOrEmpty(any())).willReturn(false);
netconfConnectDeviceCommand.doExecute();
doNothing().when(netconfCommands).connectDevice(any(), any());
verify(netconfCommands, times(1)).connectDevice(any(), any());
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSessionListener;
import org.opendaylight.netconf.api.NetconfTerminationReason;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
import org.opendaylight.netconf.api.monitoring.SessionListener;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.netconf.util.messages.SendErrorExceptionUtil;
package org.opendaylight.netconf.impl;
import com.google.common.base.Optional;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.local.LocalAddress;
import io.netty.util.Timer;
}
@Override
+ @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
protected NetconfServerSession getSession(
NetconfServerSessionListener sessionListener, Channel channel,
NetconfHelloMessage message) {
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Collections;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
*/
package org.opendaylight.netconf.impl.mapping.operations;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
*/
package org.opendaylight.netconf.impl.mapping.operations;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
}
listeners.add(listener);
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- synchronized (AggregatedNetconfOperationServiceFactory.this) {
- listeners.remove(listener);
- CloseableUtil.closeAll(regs.values());
- for (final Map.Entry<NetconfOperationServiceFactory, AutoCloseable> reg : regs.entrySet()) {
- registrations.remove(reg.getKey(), reg.getValue());
- }
+ return () -> {
+ synchronized (AggregatedNetconfOperationServiceFactory.this) {
+ listeners.remove(listener);
+ CloseableUtil.closeAll(regs.values());
+ for (final Map.Entry<NetconfOperationServiceFactory, AutoCloseable> reg : regs.entrySet()) {
+ registrations.remove(reg.getKey(), reg.getValue());
}
}
};
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
package org.opendaylight.netconf.impl.osgi;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.w3c.dom.Document;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.impl.mapping.operations.DefaultCloseSession;
import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.util.messages.SendErrorExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
import org.opendaylight.netconf.api.monitoring.SessionListener;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
import org.opendaylight.netconf.client.SimpleNetconfClientSessionListener;
private static final int CONCURRENCY = 32;
private static final InetSocketAddress NETCONF_ADDRESS = new InetSocketAddress("127.0.0.1", 8303);
- private int nettyThreads;
- private Class<? extends Runnable> clientRunnable;
- private Set<String> serverCaps;
+ private final int nettyThreads;
+ private final Class<? extends Runnable> clientRunnable;
+ private final Set<String> serverCaps;
public ConcurrentClientsTest(int nettyThreads, Class<? extends Runnable> clientRunnable, Set<String> serverCaps) {
this.nettyThreads = nettyThreads;
doNothing().when(sessionListener).onSessionUp(any(NetconfServerSession.class));
doNothing().when(sessionListener).onSessionDown(any(NetconfServerSession.class));
doNothing().when(sessionListener).onSessionEvent(any(SessionEvent.class));
- doReturn(new AutoCloseable() {
- @Override
- public void close() throws Exception {
+ doReturn((AutoCloseable) () -> {
- }
}).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
doReturn(sessionListener).when(monitoring).getSessionListener();
doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring)
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- }
+ return () -> {
};
}
int msgLength = out.readableBytes();
int chunkCount = msgLength / ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
- if ((msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE) != 0) {
+ if (msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE != 0) {
chunkCount++;
}
+
+ byte[] endOfChunkBytes = NetconfMessageConstants.END_OF_CHUNK.getBytes(StandardCharsets.UTF_8);
for (int i = 1; i <= chunkCount; i++) {
ByteBuf recievedOutbound = (ByteBuf) messages.poll();
int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
if (i == chunkCount) {
- exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
- byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
- recievedOutbound
- .getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
- assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
+ exptHeaderLength = msgLength - ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1);
+ byte[] eom = new byte[endOfChunkBytes.length];
+ recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfChunkBytes.length, eom);
+ assertArrayEquals(endOfChunkBytes, eom);
}
byte[] header = new byte[String.valueOf(exptHeaderLength).length()
testChunkChannel.writeOutbound(this.msg);
ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();
- byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length];
- recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length,
- eom);
- assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom);
+ byte[] endOfMsgBytes = NetconfMessageConstants.END_OF_MESSAGE.getBytes(StandardCharsets.UTF_8);
+ byte[] eom = new byte[endOfMsgBytes.length];
+ recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfMsgBytes.length, eom);
+ assertArrayEquals(endOfMsgBytes, eom);
testChunkChannel.writeInbound(recievedOutbound);
NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfTerminationReason;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
import org.opendaylight.netconf.api.monitoring.SessionListener;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.w3c.dom.Document;
};
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
import org.opendaylight.netconf.nettyutil.handler.NetconfEXICodec;
import org.opendaylight.netconf.nettyutil.handler.NetconfEXIToMessageDecoder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfTerminationReason;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.impl.NetconfServerSessionListener;
import org.w3c.dom.Document;
final EventLoop eventLoop = mock(EventLoop.class);
doReturn(eventLoop).when(channel).eventLoop();
doAnswer(invocation -> {
- final Object[] args = invocation.getArguments();
- final Runnable runnable = (Runnable) args[0];
- runnable.run();
+ invocation.getArgumentAt(0, Runnable.class).run();
return null;
}).when(eventLoop).execute(any(Runnable.class));
doReturn(true).when(eventLoop).inEventLoop();
doReturn(channelFuture).when(channel).close();
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
- final ChannelFuture sendFuture = mock(ChannelFuture.class);
+ final ChannelPromise sendFuture = mock(ChannelPromise.class);
doAnswer(invocation -> {
- ((GenericFutureListener) invocation.getArguments()[0]).operationComplete(sendFuture);
+ invocation.getArgumentAt(0, GenericFutureListener.class).operationComplete(sendFuture);
return null;
}).when(sendFuture).addListener(any(GenericFutureListener.class));
- doReturn(sendFuture).when(channel).writeAndFlush(anyObject());
+ doReturn(sendFuture).when(channel).newPromise();
+ doReturn(sendFuture).when(channel).writeAndFlush(anyObject(), anyObject());
doReturn(true).when(sendFuture).isSuccess();
final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class),
AutoCloseable res = mock(AutoCloseable.class);
doThrow(NetconfDocumentedException.class).when(res).close();
DefaultCloseSession session = new DefaultCloseSession("", res);
- Document doc = XmlUtil.newDocument();
XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
- session.handleWithNoSubsequentOperations(doc, elem);
+ session.handleWithNoSubsequentOperations(XmlUtil.newDocument(), elem);
}
}
package org.opendaylight.netconf.impl.mapping.operations;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyString;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.w3c.dom.Document;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
public class AggregatedNetconfOperationServiceFactoryTest {
- private Set<Capability> factory1Caps = new HashSet<>();
- private Set<Capability> factory2Caps = new HashSet<>();
+ private final Set<Capability> factory1Caps = new HashSet<>();
+ private final Set<Capability> factory2Caps = new HashSet<>();
@Mock
private CapabilityListener listener1;
verify(autoCloseable2, times(2)).close();
}
-}
\ No newline at end of file
+}
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
+import org.opendaylight.netconf.api.capability.YangModuleCapability;
import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
verify(operationService).close();
}
-}
\ No newline at end of file
+}
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
<artifactId>xmlunit</artifactId>
</dependency>
<!-- compile dependencies -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netconf-connector</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-impl</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>sal-netconf-connector</artifactId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
package org.opendaylight.netconf.mapping.api;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.w3c.dom.Document;
/**
*/
package org.opendaylight.netconf.mapping.api;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.w3c.dom.Document;
/**
package org.opendaylight.netconf.mapping.api;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
/**
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
</dependencies>
<build>
</instructions>
</configuration>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
package org.opendaylight.netconf.monitoring;
import java.util.Collections;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
private Element getPlaceholder(final Document innerResult)
throws DocumentedException {
final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
- innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY,
+ innerResult.getDocumentElement(), XmlNetconfConstants.RPC_REPLY_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
}
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
private final NetconfMonitoringOperationService operationService;
- private static final AutoCloseable AUTO_CLOSEABLE = new AutoCloseable() {
- @Override
- public void close() throws Exception {
- // NOOP
- }
+ private static final AutoCloseable AUTO_CLOSEABLE = () -> {
+ // NOOP
};
public NetconfMonitoringOperationServiceFactory(final NetconfMonitoringOperationService operationService) {
@XmlElement(name = "namespace")
public String getNamespace() {
- return schema.getNamespace().getValue().toString();
+ return schema.getNamespace().getValue();
}
@XmlElement(name = "location")
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Document;
public class GetSchemaTest {
XmlElement.fromDomElement(XmlUtil.readXmlToElement(getSchema))));
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SchemasBuilder;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.monitoring.xml.model.NetconfState;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
</dependency>
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
</project>
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
-import io.netty.channel.DefaultChannelPromise;
+import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
import java.io.IOException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.netconf.api.NetconfExiSession;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSession;
import org.opendaylight.netconf.api.NetconfSessionListener;
import org.opendaylight.netconf.api.NetconfTerminationReason;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.nettyutil.handler.NetconfEXICodec;
import org.opendaylight.netconf.nettyutil.handler.NetconfEXIToMessageDecoder;
import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToEXIEncoder;
// Restconf writes to a netconf mountpoint execute multiple messages
// and one of these was executed from a restconf thread thus breaking ordering so
// we need to execute all messages from an EventLoop thread.
- final DefaultChannelPromise proxyFuture = new DefaultChannelPromise(channel);
- channel.eventLoop().execute(new Runnable() {
- @Override
- public void run() {
- final ChannelFuture future = channel.writeAndFlush(netconfMessage);
- future.addListener(new FutureListener<Void>() {
- @Override
- public void operationComplete(final Future<Void> future) throws Exception {
- if (future.isSuccess()) {
- proxyFuture.setSuccess();
- } else {
- proxyFuture.setFailure(future.cause());
- }
- }
- });
- if (delayedEncoder != null) {
- replaceMessageEncoder(delayedEncoder);
- delayedEncoder = null;
- }
+
+ final ChannelPromise promise = channel.newPromise();
+ channel.eventLoop().execute(() -> {
+ channel.writeAndFlush(netconfMessage, promise);
+ if (delayedEncoder != null) {
+ replaceMessageEncoder(delayedEncoder);
+ delayedEncoder = null;
}
});
- return proxyFuture;
+ return promise;
}
@Override
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.nio.charset.StandardCharsets;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
public static final int DEFAULT_CHUNK_SIZE = 8192;
do {
final int xfer = Math.min(chunkSize, msg.readableBytes());
- out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
+ out.writeBytes(MessageParts.START_OF_CHUNK);
out.writeBytes(String.valueOf(xfer).getBytes(StandardCharsets.US_ASCII));
out.writeByte('\n');
out.writeBytes(msg, xfer);
} while (msg.isReadable());
- out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
+ out.writeBytes(MessageParts.END_OF_CHUNK);
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class EOMFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
out.writeBytes(msg);
- out.writeBytes(NetconfMessageConstants.END_OF_MESSAGE);
+ out.writeBytes(MessageParts.END_OF_MESSAGE);
}
}
--- /dev/null
+/*
+ * Copyright (c) 2018 Inocybe Technologies 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.netconf.nettyutil.handler;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
+
+/**
+ * netconf message part constants as bytes.
+ *
+ * @author Thomas Pantelis
+ */
+interface MessageParts {
+ byte[] END_OF_MESSAGE = NetconfMessageConstants.END_OF_MESSAGE.getBytes(UTF_8);
+ byte[] START_OF_CHUNK = NetconfMessageConstants.START_OF_CHUNK.getBytes(UTF_8);
+ byte[] END_OF_CHUNK = NetconfMessageConstants.END_OF_CHUNK.getBytes(UTF_8);
+}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class NetconfEOMAggregator extends DelimiterBasedFrameDecoder {
- public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(NetconfMessageConstants.END_OF_MESSAGE);
+ public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(MessageParts.END_OF_MESSAGE);
public NetconfEOMAggregator() {
super(Integer.MAX_VALUE, DELIMITER);
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.io.IOException;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.FailedNetconfMessage;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import com.siemens.ct.exi.exceptions.UnsupportedOption;
import com.siemens.ct.exi.helpers.DefaultEXIFactory;
import java.util.Objects;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
session = future.getSession();
final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
+ final ClientSession localSession = session;
authenticateFuture.addListener(future1 -> {
if (future1.isSuccess()) {
- handleSshAuthenticated(session, ctx);
+ handleSshAuthenticated(localSession, ctx);
} else {
// Exception does not have to be set in the future, add simple exception in such case
final Throwable exception = future1.getException() == null
// TODO we should also read from error stream and at least log from that
+ ClientChannel localChannel = channel;
sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
- msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut());
+ msg -> ctx.fireChannelRead(msg), localChannel.toString(), localChannel.getAsyncOut());
// if readAsyncListener receives immediate close,
// it will close this handler and closing this handler sets channel variable to null
this.connectPromise = promise;
if (negotiationFuture != null) {
-
negotiationFutureListener = future -> {
if (future.isSuccess()) {
- connectPromise.setSuccess();
+ promise.setSuccess();
}
};
//complete connection promise with netconf negotiation future
if (session != null && !session.isClosed() && !session.isClosing()) {
session.close(false).addListener(future -> {
- if (!future.isClosed()) {
- session.close(true);
+ synchronized (this) {
+ if (!future.isClosed()) {
+ session.close(true);
+ }
+ session = null;
}
- session = null;
});
}
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfSessionListener;
import org.opendaylight.netconf.api.NetconfSessionPreferences;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
import org.opendaylight.netconf.nettyutil.handler.EOMFramingMechanismEncoder;
import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
}
-}
\ No newline at end of file
+}
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
+import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSessionListener;
import org.opendaylight.netconf.api.NetconfTerminationReason;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
-import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
@Mock
private EventLoop eventLoop;
@Mock
- private ChannelFuture writeFuture;
+ private ChannelPromise writeFuture;
private NetconfHelloMessage clientHello;
doReturn(writeFuture).when(writeFuture).addListener(any(GenericFutureListener.class));
+ doReturn(writeFuture).when(channel).newPromise();
doReturn(writeFuture).when(channel).writeAndFlush(any(NetconfMessage.class));
+ doReturn(writeFuture).when(channel).writeAndFlush(any(NetconfMessage.class), any(ChannelPromise.class));
doReturn(pipeline).when(channel).pipeline();
doReturn("mockChannel").when(channel).toString();
doReturn(mock(ChannelFuture.class)).when(channel).close();
doReturn(null).when(pipeline).replace(anyString(), anyString(), any(ChannelHandler.class));
doReturn(eventLoop).when(channel).eventLoop();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- final Runnable runnable = (Runnable) args[0];
- runnable.run();
- return null;
- }
+ doAnswer(invocation -> {
+ invocation.getArgumentAt(0, Runnable.class).run();
+ return null;
}).when(eventLoop).execute(any(Runnable.class));
- clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
- Optional.<NetconfHelloMessageAdditionalHeader>absent());
+ clientHello = NetconfHelloMessage.createClientHello(Collections.emptySet(), Optional.absent());
}
@Test
@Test
public void testSendMessage() throws Exception {
final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L);
- final NetconfHelloMessage hello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
- Optional.<NetconfHelloMessageAdditionalHeader>absent());
+ final NetconfHelloMessage hello = NetconfHelloMessage.createClientHello(Collections.emptySet(),
+ Optional.absent());
testingNetconfSession.sendMessage(hello);
- verify(channel).writeAndFlush(hello);
+ verify(channel).writeAndFlush(hello, writeFuture);
}
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Test;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
public class EOMFramingMechanismEncoderTest {
final ByteBuf destination = Unpooled.buffer();
new EOMFramingMechanismEncoder().encode(null, source, destination);
- assertEquals(Unpooled.wrappedBuffer(source.array(), NetconfMessageConstants.END_OF_MESSAGE), destination);
+ assertEquals(Unpooled.wrappedBuffer(source.array(), MessageParts.END_OF_MESSAGE), destination);
}
-}
\ No newline at end of file
+}
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
public class NetconfEXIHandlersTest {
XMLUnit.compareXML(msg.getDocument(), ((NetconfMessage) out.get(0)).getDocument());
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.netconf.api.xml.XmlUtil;
public class NetconfHelloMessageToXMLEncoderTest {
"<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, null);
}
-}
\ No newline at end of file
+}
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
public class NetconfXMLToHelloMessageDecoderTest {
NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder();
decoder.decode(null, msg1, out);
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
@RunWith(Parameterized.class)
public class EXIParametersTest {
assertEquals(fidelity, factory.getFidelityOptions());
assertEquals(coding, factory.getCodingMode());
}
-}
\ No newline at end of file
+}
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
package org.opendaylight.netconf.notifications;
import com.google.common.base.Preconditions;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.text.ParsePosition;
import java.time.Instant;
import java.time.LocalDateTime;
/**
* Create new notification with provided timestamp.
*/
+ @SuppressFBWarnings("EI_EXPOSE_REP2") // stores a reference to an externally mutable Date object
public NetconfNotification(final Document notificationContent, final Date eventTime) {
super(wrapNotification(notificationContent, eventTime));
this.eventTime = eventTime;
*
* @return notification event time
*/
+ @SuppressFBWarnings("EI_EXPOSE_REP")
public Date getEventTime() {
return eventTime;
}
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</instructions>
</configuration>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
</project>
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfSession;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.SessionAwareNetconfOperation;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.netconf.notifications.NetconfNotificationListener;
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
private static Element getPlaceholder(final Document innerResult)
throws DocumentedException {
final XmlElement rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(),
- XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import java.io.IOException;
import javassist.ClassPool;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.mdsal.binding.dom.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.netconf.util.NetconfUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.$YangModuleInfoImpl;
private static RpcDefinition findCreateSubscriptionRpc() {
return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(),
- new Predicate<RpcDefinition>() {
- @Override
- public boolean apply(final RpcDefinition input) {
- return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
- }
- }), null);
+ input -> input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION)), null);
}
/**
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.api.util.NetconfConstants;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
listener.onCapabilitiesChanged(capabilities, Collections.<Capability>emptySet());
- return new AutoCloseable() {
- @Override
- public void close() {
- listener.onCapabilitiesChanged(Collections.<Capability>emptySet(), capabilities);
- }
- };
+ return () -> listener.onCapabilitiesChanged(Collections.<Capability>emptySet(), capabilities);
}
@Override
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfSession;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.notifications.NetconfNotificationListener;
import org.opendaylight.netconf.notifications.NetconfNotificationRegistry;
import org.opendaylight.netconf.notifications.NotificationListenerRegistration;
Assert.assertThat(XmlUtil.toString(element), CoreMatchers.containsString("ok"));
}
-}
\ No newline at end of file
+}
import com.google.common.collect.Lists;
import java.io.IOException;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.StreamsBuilder;
+ "</data>\n"
+ "</rpc-reply>");
}
-}
\ No newline at end of file
+}
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
import java.util.Set;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.api.util.NetconfConstants;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
<propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
</configuration>
</plugin>
-<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<failOnError>true</failOnError>
</configuration>
</plugin>
--->
</plugins>
</build>
</project>
<name>${project.artifactId}</name>
<packaging>bundle</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-impl</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-config-api</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
package org.opendaylight.netconf.ssh;
-import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
+import java.nio.charset.StandardCharsets;
import org.apache.sshd.common.io.IoInputStream;
import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.server.ExitCallback;
writeAdditionalHeader(ctx);
asyncSshHandlerWriter = new AsyncSshHandlerWriter(out);
- asyncSshHandlerReader = new AsyncSshHandlerReader(new AutoCloseable() {
- @Override
- public void close() throws Exception {
- // Close both sessions (delegate server and remote client)
- ctx.fireChannelInactive();
- ctx.disconnect();
- ctx.close();
- asyncSshHandlerReader.close();
- asyncSshHandlerWriter.close();
- }
- }, new AsyncSshHandlerReader.ReadMsgHandler() {
- @Override
- public void onMessageRead(final ByteBuf msg) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
- netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
- AsyncSshHandlerWriter.byteBufToString(msg));
- }
- // Just forward to delegate
- ctx.writeAndFlush(msg);
+ asyncSshHandlerReader = new AsyncSshHandlerReader(() -> {
+ // Close both sessions (delegate server and remote client)
+ ctx.fireChannelInactive();
+ ctx.disconnect();
+ ctx.close();
+ asyncSshHandlerReader.close();
+ asyncSshHandlerWriter.close();
+ }, msg -> {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
+ netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
+ AsyncSshHandlerWriter.byteBufToString(msg));
}
+ // Just forward to delegate
+ ctx.writeAndFlush(msg);
}, "ssh" + netconfHelloMessageAdditionalHeader.getAddress(), in);
}
private void writeAdditionalHeader(final ChannelHandlerContext ctx) {
- ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString().getBytes()));
+ ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString()
+ .getBytes(StandardCharsets.UTF_8)));
}
@Override
import io.netty.channel.EventLoopGroup;
import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
sshServer.start();
}
- private static Map<String, String> getProperties(final SshProxyServerConfiguration sshProxyServerConfiguration) {
- final Map<String, String> ret = new HashMap<>();
- ret.put(ServerFactoryManager.IDLE_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
- // TODO make auth timeout configurable on its own
- ret.put(ServerFactoryManager.AUTH_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
-
- return ret;
- }
-
@Override
public void close() throws IOException {
try {
<name>${project.artifactId}</name>
<packaging>bundle</packaging>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-util</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-config-api</artifactId>
- </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
</project>
<artifactId>akka-testkit_2.12</artifactId>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
private NetconfNodeManager netconfNodeManager;
private ActorRef masterActorRef;
private boolean finalClose = false;
- private boolean closed = false;
+ private final AtomicBoolean closed = new AtomicBoolean(false);
private boolean isMaster;
NetconfTopologyContext(final NetconfTopologySetup netconfTopologyDeviceSetup,
}
}
- private synchronized void stopDeviceConnectorAndActor() {
- if (closed) {
+ private void stopDeviceConnectorAndActor() {
+ if (!closed.compareAndSet(false, true)) {
return;
}
if (remoteDeviceConnector != null) {
netconfTopologyDeviceSetup.getActorSystem().stop(masterActorRef);
masterActorRef = null;
}
- closed = true;
}
}
NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
final ActorRef deviceContextActorRef) {
//setup default values since default value is not supported in mdsal
- final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+ final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
- final Long keepaliveDelay = node.getKeepaliveDelay() == null
+ final long keepaliveDelay = node.getKeepaliveDelay() == null
? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
- final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+ final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
@Override
public ReconnectStrategy createReconnectStrategy() {
- final Long maxSleep = null;
- final Long deadline = null;
-
return new TimedReconnectStrategy(executor, minSleep,
- minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
+ minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
}
}
}
Futures.addCallback(remoteSchemaContext, new FutureCallback<SchemaContext>() {
@Override
- public void onSuccess(final SchemaContext result) {
+ public void onSuccess(@Nonnull final SchemaContext result) {
LOG.info("{}: Schema context resolved: {}", id, result.getModules());
slaveSalManager.registerSlaveMountPoint(result, deviceRpcService, masterReference);
}
Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
@Override
- public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
+ public void onSuccess(@Nonnull final Optional<NormalizedNode<?, ?>> result) {
if (!result.isPresent()) {
sender.tell(new EmptyReadResponse(), self);
return;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemasResolverImpl;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
package org.opendaylight.netconf.topology.singleton.messages;
-import java.io.Serializable;
import java.util.List;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
/**
* Master sends this message to the own actor to set necessary parameters.
*/
-public class CreateInitialMasterActorData implements Serializable {
- private static final long serialVersionUID = 1L;
-
+public class CreateInitialMasterActorData {
private final DOMDataBroker deviceDataBroker;
private final List<SourceIdentifier> allSourceIdentifiers;
private final DOMRpcService deviceRpc;
package org.opendaylight.netconf.topology.singleton.messages;
-import java.io.Serializable;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
/**
* Master sends this message to the own actor to refresh setup data.
*/
-public class RefreshSetupMasterActorData implements Serializable {
- private static final long serialVersionUID = 1L;
-
+public class RefreshSetupMasterActorData {
private final NetconfTopologySetup netconfTopologyDeviceSetup;
private final RemoteDeviceId remoteDeviceId;
package org.opendaylight.netconf.topology.singleton.messages;
import akka.util.Timeout;
-import java.io.Serializable;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-public class RefreshSlaveActor implements Serializable {
+public class RefreshSlaveActor {
private final SchemaRepository schemaRepository;
private final RemoteDeviceId id;
package org.opendaylight.netconf.topology.singleton.messages;
import com.google.common.collect.Iterables;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
public class SchemaPathMessage implements Serializable {
private static final long serialVersionUID = 1L;
- private SchemaPath schemaPath;
+ @SuppressFBWarnings("SE_BAD_FIELD")
+ private final SchemaPath schemaPath;
public SchemaPathMessage(final SchemaPath schemaPath) {
this.schemaPath = schemaPath;
private SchemaPathMessage schemaPathMessage;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
private InvokeRpcMessage invokeRpcMessage;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
package org.opendaylight.netconf.topology.singleton.messages.rpc;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
public class InvokeRpcMessageReply implements Serializable {
private static final long serialVersionUID = 1L;
+ @SuppressFBWarnings("SE_BAD_FIELD")
private final Collection<RpcError> rpcErrors;
private final NormalizedNodeMessage normalizedNodeMessage;
private InvokeRpcMessageReply invokeRpcMessageReply;
- Proxy() {
+ @SuppressWarnings("checkstyle:RedundantModifier")
+ public Proxy() {
//due to Externalizable
}
import java.io.Serializable;
public class NewReadTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewReadTransactionRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
}
import java.io.Serializable;
public class NewReadWriteTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewWriteTransactionReply implements Serializable {
+ private static final long serialVersionUID = 1L;
private final ActorRef txActor;
import java.io.Serializable;
public class NewWriteTransactionRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
}
}
-}
\ No newline at end of file
+}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
<version>0.8.0-SNAPSHOT</version>
</dependency>
</dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
final NetconfNode node) {
//setup default values since default value is not supported in mdsal
- final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+ final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
- final Long keepaliveDelay = node.getKeepaliveDelay() == null
+ final long keepaliveDelay = node.getKeepaliveDelay() == null
? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
- final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+ final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
final IpAddress ipAddress = node.getHost().getIpAddress();
@Override
public ReconnectStrategy createReconnectStrategy() {
- final Long maxSleep = null;
- final Long deadline = null;
-
return new TimedReconnectStrategy(executor, minSleep,
- minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
+ minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
}
}
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
public static Document checkIsMessageOk(final Document response) throws DocumentedException {
XmlElement element = XmlElement.fromDomDocument(response);
- Preconditions.checkState(element.getName().equals(XmlMappingConstants.RPC_REPLY_KEY));
+ Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
element = element.getOnlyChildElement();
if (element.getName().equals(XmlNetconfConstants.OK)) {
return response;
*/
package org.opendaylight.netconf.util.mapping;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.w3c.dom.Document;
import com.google.common.base.Optional;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
Map<String, Attr> attributes = requestElement.getAttributes();
Element response = handle(document, operationElement, subsequentOperation);
- Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+ Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY,
Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
if (XmlElement.fromDomElement(response).hasNamespace()) {
*/
package org.opendaylight.netconf.util.mapping;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.w3c.dom.Document;
package org.opendaylight.netconf.util.messages;
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-public final class NetconfMessageConstants {
-
- private NetconfMessageConstants(){}
+public interface NetconfMessageConstants {
/**
* The NETCONF 1.0 old-style message separator. This is framing mechanism
* is used by default.
*/
- public static final byte[] END_OF_MESSAGE = "]]>]]>".getBytes(UTF_8);
+ String END_OF_MESSAGE = "]]>]]>";
// bytes
- public static final int MIN_HEADER_LENGTH = 4;
+ int MIN_HEADER_LENGTH = 4;
// bytes
- public static final int MAX_HEADER_LENGTH = 13;
-
- public static final byte[] START_OF_CHUNK = "\n#".getBytes(UTF_8);
- public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(UTF_8);
+ int MAX_HEADER_LENGTH = 13;
+ String START_OF_CHUNK = "\n#";
+ String END_OF_CHUNK = "\n##\n";
}
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSession;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
"Missing %s element", XmlNetconfConstants.RPC_KEY);
final Element rpcReply = errorDocument.getDocumentElement();
- Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY),
- "Missing %s element", XmlMappingConstants.RPC_REPLY_KEY);
+ Preconditions.checkState(rpcReply.getTagName().equals(XmlNetconfConstants.RPC_REPLY_KEY),
+ "Missing %s element", XmlNetconfConstants.RPC_REPLY_KEY);
final NamedNodeMap incomingAttributes = incommingRpc.getAttributes();
for (int i = 0; i < incomingAttributes.getLength(); i++) {
import com.google.common.base.Optional;
import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.util.mapping.AbstractNetconfOperation.OperationNameAndNamespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.$YangModuleInfoImpl;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Sessions;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.w3c.dom.Document;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.netconf.util.test.XmlFileLoader;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSession;
import org.opendaylight.netconf.util.test.XmlFileLoader;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.ParserConfigurationException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import org.custommonkey.xmlunit.NodeTest;
import org.custommonkey.xmlunit.NodeTestException;
import org.custommonkey.xmlunit.NodeTester;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Element;
public class XMLNetconfUtilTest {
assertEquals("value", ((Element) value).getTextContent());
}
-}
\ No newline at end of file
+}
<module>netconf-api</module>
<module>netconf-config</module>
<module>netconf-impl</module>
- <module>config-netconf-connector</module>
<module>mdsal-netconf-ssh</module>
<module>mdsal-netconf-tcp</module>
<module>mdsal-netconf-connector</module>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netconf-connector</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-impl</artifactId>
<tag>HEAD</tag>
<url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
</scm>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- </build>
</project>
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collections;
+import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
/**
* Holds URLs with YANG schema resources for all yang modules reported in
if (connection instanceof HttpURLConnection) {
connection.setRequestProperty("Accept", "application/xml");
final String userpass = username + ":" + password;
- final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
+ final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", basicAuth);
}
String extension = "";
final int i = fileName.lastIndexOf(46);
if (i != -1) {
- extension = fileName.substring(i).toLowerCase();
+ extension = fileName.substring(i).toLowerCase(Locale.ROOT);
}
return extension.equals(".json");
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
- final JsonReader reader = new JsonReader(new InputStreamReader(in));
+ final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
jsonParser.parse(reader);
return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
}
- @SuppressWarnings("checkstyle:IllegalCatch")
private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
try {
final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
final NormalizedNode<?, ?> parsed = resultHolder.getResult();
return Optional.of(parsed);
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
LOG.warn("Unable to parse yang library xml content", e);
}
private static Optional<String> getValueOfSimpleNode(
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
- final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty()
- : Optional.of(value.toString().trim());
+ final String valueStr = node.getValue().toString();
+ return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
}
@Override
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
@Override
- public void onSuccess(final DeviceSources result) {
+ public void onSuccess(@Nonnull final DeviceSources result) {
addProvidedSourcesToSchemaRegistry(result);
setUpSchema(result);
}
updateTransformer(null);
}
- private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
+ private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
messageTransformer = transformer;
}
if (cause instanceof MissingSchemaSourceException) {
requiredSources = handleMissingSchemaSourceException(
- requiredSources, (MissingSchemaSourceException) e.getCause());
+ requiredSources, (MissingSchemaSourceException) cause);
continue;
}
if (cause instanceof SchemaResolutionException) {
private static Optional<String> getValueOfSimpleNode(
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
- final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString())
- ? Optional.empty() : Optional.of(value.toString().trim());
+ final String valueStr = node.getValue().toString();
+ return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
}
@Override
import com.google.common.base.Preconditions;
import java.util.LinkedList;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.FailedNetconfMessage;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfTerminationReason;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.client.NetconfClientSession;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
try {
request = requests.peek();
if (request != null && request.future.isUncancellable()) {
- requests.poll();
+ request = requests.poll();
// we have just removed one request from the queue
// we can also release one permit
if (semaphore != null) {
@Override
public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
sessionLock.lock();
-
- if (semaphore != null && !semaphore.tryAcquire()) {
- LOG.warn("Limit of concurrent rpc messages was reached (limit :"
- + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id"
- + id.getName());
- sessionLock.unlock();
- return Futures.immediateFailedFuture(new NetconfDocumentedException(
- "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
- + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
- }
-
try {
+ if (semaphore != null && !semaphore.tryAcquire()) {
+ LOG.warn("Limit of concurrent rpc messages was reached (limit :" + concurentRpcMsgs
+ + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
+ return Futures.immediateFailedFuture(new NetconfDocumentedException(
+ "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
+ + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
+ }
+
return sendRequestWithLock(message, rpc);
} finally {
sessionLock.unlock();
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractFuture;
import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
final class UncancellableFuture<V> extends AbstractFuture<V> {
- @GuardedBy("this")
- private boolean uncancellable = false;
+ private volatile boolean uncancellable = false;
UncancellableFuture(final boolean uncancellable) {
this.uncancellable = uncancellable;
}
- public synchronized boolean setUncancellable() {
+ public boolean setUncancellable() {
if (isCancelled()) {
return false;
}
return true;
}
- public synchronized boolean isUncancellable() {
+ public boolean isUncancellable() {
return uncancellable;
}
@Override
- public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+ public boolean cancel(final boolean mayInterruptIfRunning) {
return !uncancellable && super.cancel(mayInterruptIfRunning);
}
@Override
- public synchronized boolean set(@Nullable final V value) {
+ public boolean set(@Nullable final V value) {
Preconditions.checkState(uncancellable);
return super.set(value);
}
if (result != null && result.getResult() != null) {
LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
scheduleKeepalive();
- } else if (result != null && result.getErrors() != null) {
+ } else if (result != null && !result.getErrors().isEmpty()) {
LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
scheduleKeepalive();
} else {
- LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
+ LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
reconnect();
}
}
public static final class KeepaliveDOMRpcService implements DOMRpcService {
private final DOMRpcService deviceRpc;
- private ResetKeepalive resetKeepaliveTask;
+ private final ResetKeepalive resetKeepaliveTask;
private final long defaultRequestTimeoutMillis;
private final ScheduledExecutorService executor;
*/
package org.opendaylight.netconf.sal.connect.netconf.sal;
-import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
}
}, MoreExecutors.directExecutor());
- return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
- @Nullable
- @Override
- public DOMRpcException apply(@Nullable final Exception exception) {
- return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type);
- }
- });
+ return Futures.makeChecked(transformed, exception ->
+ new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type));
}
@Nonnull
}, MoreExecutors.directExecutor());
}
- private static Node getNodeWithId(final RemoteDeviceId id) {
- final NodeBuilder builder = getNodeIdBuilder(id);
- return builder.build();
- }
-
private static NodeBuilder getNodeIdBuilder(final RemoteDeviceId id) {
final NodeBuilder nodeBuilder = new NodeBuilder();
nodeBuilder.setKey(new NodeKey(new NodeId(id.getName())));
*/
package org.opendaylight.netconf.sal.connect.netconf.sal;
-import com.google.common.base.Function;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
listener.sendRequest(netconfMessage, type.getLastComponent());
final ListenableFuture<DOMRpcResult> transformed =
- Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
+ Futures.transform(rpcResultListenableFuture, input1 -> {
if (input1.isSuccessful()) {
return transformer.toRpcResult(input1.getResult(), type);
- } else {
- return new DefaultDOMRpcResult(input1.getErrors());
}
+
+ return new DefaultDOMRpcResult(input1.getErrors());
}, MoreExecutors.directExecutor());
- return Futures.makeChecked(transformed,
- e -> new DOMRpcImplementationNotAvailableException(e,
+ return Futures.makeChecked(transformed, e -> new DOMRpcImplementationNotAvailableException(e,
"Unable to invoke rpc %s on device %s", type, deviceId));
}
public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T lsnr) {
throw new UnsupportedOperationException("Not available for netconf 1.0");
}
-
}
import com.google.common.util.concurrent.SettableFuture;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
-import javax.annotation.Nullable;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
// Allow commit to be called only once
- protected boolean finished = false;
+ protected volatile boolean finished = false;
public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
this.netOps = netOps;
final DataContainerChild<?, ?> editStructure =
netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
Optional.of(ModifyAction.REPLACE), path);
- editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
+ editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "put");
}
@Override
final ListenableFuture<RpcResult<Void>> result = performCommit();
Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
@Override
- public void onSuccess(@Nullable final RpcResult<Void> result) {
- if (result != null && result.isSuccessful()) {
+ public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
+ if (rpcResult.isSuccessful()) {
listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
} else {
final TransactionCommitFailedException cause =
new TransactionCommitFailedException("Transaction failed",
- result.getErrors().toArray(new RpcError[result.getErrors().size()]));
+ rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
}
}
Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
@Override
- public void onSuccess(final List<DOMRpcResult> domRpcResults) {
+ public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
domRpcResults.forEach(domRpcResult -> {
if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
final NetconfDocumentedException exception =
package org.opendaylight.netconf.sal.connect.netconf.sal.tx;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
private void lock() {
final FutureCallback<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
@Override
- public void onSuccess(final DOMRpcResult result) {
+ public void onSuccess(@Nonnull final DOMRpcResult result) {
if (isSuccess(result)) {
if (LOG.isTraceEnabled()) {
LOG.trace("Lock candidate successful");
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
- final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commitConfiguration(),
- (Function<RpcResult<Void>, Void>) input -> {
- Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
- "Submit failed with errors: %s", input.getErrors());
- return null;
- }, MoreExecutors.directExecutor());
+ final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commitConfiguration(), input -> {
+ Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
+ "Submit failed with errors: %s", input.getErrors());
+ return null;
+ }, MoreExecutors.directExecutor());
return Futures.makeChecked(commitFutureAsVoid, input -> new TransactionCommitFailedException(
"Submit of transaction " + getIdentifier() + " failed", input));
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import javax.annotation.Nonnull;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
}
@Override
- public YangTextSchemaSource apply(final DOMRpcResult input) {
+ public YangTextSchemaSource apply(@Nonnull final DOMRpcResult input) {
if (input.getErrors().isEmpty()) {
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.nio.charset.Charset;
import java.util.Map;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
private ListenableFuture<? extends YangTextSchemaSource> download(final SourceIdentifier sourceIdentifier) {
final URL url = availableSources.get(sourceIdentifier);
try (InputStream in = url.openStream()) {
- final String schemaContent = new String(ByteStreams.toByteArray(in));
+ final String schemaContent = new String(ByteStreams.toByteArray(in), Charset.defaultCharset());
final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
new NetconfRemoteSchemaYangSourceProvider
.NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
final DOMResult result = domResult;
try {
- NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result,
+ NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result,
inputPath, SCHEMA_CONTEXT);
} catch (final XMLStreamException | IOException | IllegalStateException e) {
throw new IllegalStateException("Unable to serialize " + inputPath, e);
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.io.IOException;
+import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import javax.annotation.Nonnull;
+import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
this.strictParsing = strictParsing;
}
- @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public synchronized DOMNotification toNotification(final NetconfMessage message) {
final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
notificationAsContainerSchemaNode, strictParsing);
xmlParser.traverse(new DOMSource(element));
content = (ContainerNode) resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException | UnsupportedOperationException e) {
throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
}
return new NetconfDeviceNotification(content, stripped.getKey());
|| rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
}
- @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
final NormalizedNode<?, ?> normalizedNode;
strictParsing);
xmlParser.traverse(new DOMSource(xmlData));
dataNode = (ContainerNode) resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
}
rpcDefinition.getOutput(), strictParsing);
xmlParser.traverse(new DOMSource(element));
normalizedNode = resultHolder.getResult();
- } catch (final Exception e) {
+ } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+ | SAXException e) {
throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
}
}
import java.util.Date;
import java.util.Map;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
+import java.util.Locale;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade.KeepaliveDOMRpcService;
// Default operation
if (defaultOperation.isPresent()) {
- final String opString = defaultOperation.get().name().toLowerCase();
+ final String opString = defaultOperation.get().name().toLowerCase(Locale.ROOT);
editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
.withValue(opString).build());
}
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.FailedNetconfMessage;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import org.opendaylight.netconf.util.NetconfUtil;
package org.opendaylight.netconf.sal.connect.netconf.util;
import com.google.common.util.concurrent.FutureCallback;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.slf4j.Logger;
}
@Override
- public void onSuccess(final DOMRpcResult result) {
+ public void onSuccess(@Nonnull final DOMRpcResult result) {
if (result.getErrors().isEmpty()) {
LOG.trace("{}: {} invoked successfully", id, type);
} else {
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Map.Entry;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId =
(YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument;
final Map<QName, Object> keyValues = keyedId.getKeyValues();
- for (QName qualifiedName : keyValues.keySet()) {
+ for (Entry<QName, Object> entry : keyValues.entrySet()) {
+ QName qualifiedName = entry.getKey();
final List<XmlElement> key =
dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(),
qualifiedName.getNamespace().toString());
} catch (DocumentedException e) {
throw new IllegalStateException("Key value not present in key element", e);
}
- if (!keyValues.get(qualifiedName).equals(textContent)) {
+ if (!entry.getValue().equals(textContent)) {
throw new IllegalStateException("Key value in path not equal to key value in xml");
}
}
}
private static String toOperationString(final ModifyAction operation) {
- return operation.name().toLowerCase();
+ return operation.name().toLowerCase(Locale.ROOT);
}
private static Element getSourceElement(final DOMSource source) {
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.notifications.NetconfNotification;
import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfTerminationReason;
+import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
import org.opendaylight.netconf.client.NetconfClientSession;
import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
throws ParserConfigurationException {
Document doc = UntrustedXML.newDocumentBuilder().newDocument();
Element rpcReply =
- doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
+ doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.RPC_REPLY_KEY);
rpcReply.setAttribute("message-id", messageID);
Element element = doc.createElementNS("ns", "data");
element.setTextContent(messageID);
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcIdentifier;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017._private.keys.PrivateKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017._private.keys.PrivateKeyBuilder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseRpcSchemalessTransformer;
import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.SchemalessMessageTransformer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget;
Assert.assertTrue(diff.toString(), diff.similar());
}
-}
\ No newline at end of file
+}
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import org.opendaylight.yangtools.yang.common.QName;
Assert.assertNull(result.getResult());
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.aaa.encrypt.AAAEncryptionService;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.util.NetconfSalKeystoreService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.AddPrivateKeyInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.AddPrivateKeyInputBuilder;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
<sonar.skip>true</sonar.skip>
</properties>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<dependencies>
<dependency>
<groupId>org.codehaus.janino</groupId>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-auth</artifactId>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netconf-connector</artifactId>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>sal-netconf-connector</artifactId>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-ssh</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-config-api</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-inmemory-datastore</artifactId>
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.Set;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
public class DummyMonitoringService implements NetconfMonitoringService {
private static final Sessions EMPTY_SESSIONS = new SessionsBuilder().setSession(Collections.emptyList()).build();
- private static final Function<Capability, Uri> CAPABILITY_URI_FUNCTION = new Function<Capability, Uri>() {
- @Nullable
- @Override
- public Uri apply(Capability capability) {
- return new Uri(capability.getCapabilityUri());
- }
- };
+ private static final Function<Capability, Uri> CAPABILITY_URI_FUNCTION =
+ capability -> new Uri(capability.getCapabilityUri());
private static final Function<Capability, Schema> CAPABILITY_SCHEMA_FUNCTION = new Function<Capability, Schema>() {
@Nullable
@Override
- public Schema apply(@Nullable Capability capability) {
+ public Schema apply(@Nonnull Capability capability) {
return new SchemaBuilder()
.setIdentifier(capability.getModuleName().get())
.setNamespace(new Uri(capability.getModuleNamespace().get()))
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseStatus;
-import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
}
private void invokeAsync() {
- final ArrayList<ListenableFuture<Response>> futures = new ArrayList<>();
LOG.info("Begin sending async requests");
for (final Request request : payloads) {
} catch (InterruptedException e) {
LOG.warn("Semaphore acquire interrupted");
}
- futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
+ asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
@Override
public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
super.onStatusReceived(status);
semaphore.release();
return response;
}
- }));
+ });
}
LOG.info("Requests sent, waiting for responses");
package org.opendaylight.netconf.test.tool;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.YangModuleCapability;
/**
* Can be passed instead of YangModuleCapability when building capabilities
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public final class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
}
@SuppressWarnings("checkstyle:IllegalCatch")
+ @SuppressFBWarnings({"UW_UNCOND_WAIT", "WA_NOT_IN_LOOP"})
public static void main(final String[] args) {
final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
params.validate();
} else {
try {
future.get();
- } catch (final ExecutionException e) {
+ } catch (final ExecutionException | InterruptedException e) {
LOG.info("{}. thread failed.", threadNum, e);
}
}
configGenerator.updateFeatureFile(generated);
configGenerator.changeLoadOrder();
}
- } catch (final Exception e) {
+ } catch (RuntimeException | InterruptedException e) {
LOG.error("Unhandled exception", e);
netconfDeviceSimulator.close();
System.exit(1);
Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
}
- for (final File file : configDir.listFiles(pathname ->
- !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX))) {
- Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
+ final File[] files = configDir.listFiles(pathname ->
+ !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX));
+ if (files != null) {
+ for (final File file : files) {
+ Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
+ }
}
try (InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
String configContent = String.format(
middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
configContent = String.format(
- "%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>",
+ "%s%s%d%s%n%s%n", configContent, "<connection-timeout-millis>",
generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
builder.append(configContent);
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
-import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.impl.SessionIdProvider;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.local.LocalAddress;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.util.security.SecurityUtils;
import org.apache.sshd.common.util.threads.ThreadUtils;
-import org.opendaylight.controller.config.util.capability.BasicCapability;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
+import org.opendaylight.netconf.api.capability.BasicCapability;
+import org.opendaylight.netconf.api.capability.Capability;
+import org.opendaylight.netconf.api.capability.YangModuleCapability;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public class NetconfDeviceSimulator implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
import com.ning.http.client.AsyncHttpClientConfig.Builder;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.opendaylight.netconf.test.tool.config.Configuration;
import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
public final class ScaleUtil {
private static final ScheduledExecutorService EXECUTOR = new LoggingWrapperExecutor(4);
private static final Semaphore SEMAPHORE = new Semaphore(0);
root.error("Failed to start any simulated devices, exiting...");
System.exit(1);
}
- if (params.distroFolder != null) {
- final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
- params.distroFolder, openDevices);
- final List<File> generated = configGenerator.generate(
- params.ssh, params.generateConfigBatchSize,
- params.generateConfigsTimeout, params.generateConfigsAddress,
- params.devicesPerPort);
- configGenerator.updateFeatureFile(generated);
- configGenerator.changeLoadOrder();
+
+ if (params.distroFolder == null) {
+ root.error("Distro folder is not set, exiting...");
+ System.exit(1);
}
+
+ final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
+ params.distroFolder, openDevices);
+ final List<File> generated = configGenerator.generate(
+ params.ssh, params.generateConfigBatchSize,
+ params.generateConfigsTimeout, params.generateConfigsAddress,
+ params.devicesPerPort);
+ configGenerator.updateFeatureFile(generated);
+ configGenerator.changeLoadOrder();
} catch (final Exception e) {
root.error("Unhandled exception", e);
netconfDeviceSimulator.close();
if (f.isDirectory()) {
deleteFolder(f);
} else {
- f.delete();
+ if (!f.delete()) {
+ root.warn("Failed to delete {}", f);
+ }
}
}
}
- folder.delete();
- }
-
- private static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
- final TesttoolParameters parameters = new TesttoolParameters();
- try {
- parser.parseArgs(args, parameters);
- return parameters;
- } catch (ArgumentParserException e) {
- parser.handleError(e);
+ if (!folder.delete()) {
+ root.warn("Failed to delete {}", folder);
}
-
- System.exit(1);
- return null;
}
private static class ScaleVerifyCallable implements Callable {
return new LogOnExceptionCallable(callable);
}
- private class LogOnExceptionCallable implements Callable {
- private Callable theCallable;
+ private static class LogOnExceptionCallable implements Callable {
+ private final Callable theCallable;
LogOnExceptionCallable(Callable theCallable) {
this.theCallable = theCallable;
import java.io.File;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.impl.SessionIdProvider;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
public AutoCloseable registerCapabilityListener(
final CapabilityListener listener) {
listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- }
+ return () -> {
};
}
import com.google.common.base.Preconditions;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
+@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
public class TesttoolParameters {
private static final String HOST_KEY = "{HOST}";
checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
- final List<File> files = Arrays.asList(schemasDir.listFiles());
+ final File[] filesArray = schemasDir.listFiles();
+ final List<File> files = filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList();
for (final File file : files) {
final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
if (!matcher.matches()) {
- final BufferedReader reader;
- try {
- reader = new BufferedReader(new FileReader(file));
+ try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = reader.readLine();
while (!DATE_PATTERN.matcher(line).find()) {
line = reader.readLine();
final String revision = m.group(1);
final String correctName = moduleName + "@" + revision + ".yang";
final File correctNameFile = new File(correctName);
- file.renameTo(correctNameFile);
+ if (!file.renameTo(correctNameFile)) {
+ System.err.println("Failed to rename " + file);
+ }
}
} catch (final IOException e) {
// print error to console (test tool is running from console)
final int batchedRequests = openDevices.size() / generateConfigBatchSize;
final int batchedRequestsPerThread = batchedRequests / threadAmount;
- final int leftoverBatchedRequests = (batchedRequests) % threadAmount;
- final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize);
+ final int leftoverBatchedRequests = batchedRequests % threadAmount;
+ final int leftoverRequests = openDevices.size() - batchedRequests * generateConfigBatchSize;
final StringBuilder destBuilder = new StringBuilder(DEST);
destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
controllerDestination);
for (int l = 0; l < threadAmount; l++) {
- from = l * (batchedRequests * batchedRequestsPerThread);
- to = from + (batchedRequests * batchedRequestsPerThread);
+ from = l * batchedRequests * batchedRequestsPerThread;
+ to = from + batchedRequests * batchedRequestsPerThread;
iterator = openDevices.subList(from, to).iterator();
allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString,
destBuilder.toString()));
}
ArrayList<Execution.DestToPayload> payloads = null;
if (leftoverBatchedRequests > 0) {
- from = threadAmount * (batchedRequests * batchedRequestsPerThread);
- to = from + (batchedRequests * batchedRequestsPerThread);
+ from = threadAmount * batchedRequests * batchedRequestsPerThread;
+ to = from + batchedRequests * batchedRequestsPerThread;
iterator = openDevices.subList(from, to).iterator();
payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString,
destBuilder.toString());
}
if (leftoverRequests > 0) {
- from = (threadAmount) * requestPerThreads;
+ from = threadAmount * requestPerThreads;
to = from + leftoverRequests;
iterator = openDevices.subList(from, to).iterator();
allThreadsPayloads.add(createPayloads(iterator, editContentString));
final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
for (int i = 0; i < batchedRequestsCount; i++) {
- String payload = "";
+ StringBuilder payload = new StringBuilder();
for (int j = 0; j < generateConfigBatchSize; j++) {
final StringBuilder payloadBuilder = new StringBuilder(
prepareMessage(openDevices.next(), editContentString));
- payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize);
+ payload.append(modifyMessage(payloadBuilder, j, generateConfigBatchSize));
}
- payloads.add(new Execution.DestToPayload(destination, payload));
+ payloads.add(new Execution.DestToPayload(destination, payload.toString()));
}
return payloads;
}
import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.HttpResponseStatus;
-import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
import java.util.ArrayList;
@Override
public void invoke() {
- final ArrayList<ListenableFuture<Response>> futures = new ArrayList<>();
LOG.info("Begin sending async requests");
for (final Request request : payloads) {
} catch (InterruptedException e) {
LOG.warn("Semaphore acquire interrupted");
}
- futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
+ asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
@Override
public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
super.onStatusReceived(status);
semaphore.release();
return response;
}
- }));
+ });
}
LOG.info("Requests sent, waiting for responses");
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_EXIT")
public final class RestPerfClient {
private static final Logger LOG = LoggerFactory.getLogger(RestPerfClient.class);
// and do not log it
if (allThreadsCompleted) {
LOG.info(
- "Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
+ "Requests per second: {}", parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS));
}
System.exit(0);
}
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
int batchI = 0;
for (final Integer editBatch : getEditBatches()) {
for (int i = 0; i < editBatch; i++) {
- final int msgId = i + (batchI * getParams().editBatchSize);
+ final int msgId = i + batchI * getParams().editBatchSize;
final NetconfMessage msg = getPreparedMessages().get(msgId);
LOG.debug("Sending message {}", msgId);
if (LOG.isDebugEnabled()) {
import ch.qos.logback.classic.Level;
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import java.util.concurrent.TimeoutException;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
+@SuppressFBWarnings("DM_EXIT")
public final class StressClient {
private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
started.stop();
LOG.info("FINISHED. Execution time: {}", started);
- LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
+ LOG.info("Requests per second: {}", params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS));
// Cleanup
timer.stop();
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
super(params, preparedMessages, sessionListener);
}
+ @Override
public void invoke() {
final AtomicInteger responseCounter = new AtomicInteger(0);
int batchI = 0;
for (final Integer editBatch : getEditBatches()) {
for (int i = 0; i < editBatch; i++) {
- final int msgId = i + (batchI * getParams().editBatchSize);
+ final int msgId = i + batchI * getParams().editBatchSize;
final NetconfMessage msg = getPreparedMessages().get(msgId);
LOG.debug("Sending message {}", msgId);
if (LOG.isDebugEnabled()) {
import java.util.Optional;
import java.util.stream.Stream;
import javax.xml.bind.JAXB;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
}
}
- if (e1Children.isEmpty() && e1Children.isEmpty()) {
+ if (e1Children.isEmpty() && e2Children.isEmpty()) {
try {
return e1.getTextContent().equals(e2.getTextContent());
} catch (final DocumentedException e) {
import java.io.File;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
import java.io.File;
import java.util.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.impl.SessionIdProvider;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
package org.opendaylight.netconf.test.tool.operations;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.impl.SessionIdProvider;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.impl.SessionIdProvider;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
public AutoCloseable registerCapabilityListener(
final CapabilityListener listener) {
listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- }
+ return () -> {
};
}
import java.util.Collections;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlElement;
public class DataList {
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedCommit extends AbstractConfigNetconfOperation {
+public class SimulatedCommit extends AbstractLastNetconfOperation {
public SimulatedCommit(final String netconfSessionIdForReporting) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
}
@Override
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.impl.NetconfServerSession;
import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation;
import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedDiscardChanges extends AbstractConfigNetconfOperation {
+public class SimulatedDiscardChanges extends AbstractLastNetconfOperation {
public SimulatedDiscardChanges(final String netconfSessionIdForReporting) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
}
@Override
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedEditConfig extends AbstractConfigNetconfOperation {
+public class SimulatedEditConfig extends AbstractLastNetconfOperation {
private static final String DELETE_EDIT_CONFIG = "delete";
private static final String OPERATION = "operation";
private static final String REMOVE_EDIT_CONFIG = "remove";
private final DataList storage;
public SimulatedEditConfig(final String netconfSessionIdForReporting, final DataList storage) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
this.storage = storage;
}
@Override
protected String getOperationName() {
- return EditConfigXmlParser.EDIT_CONFIG;
+ return "edit-config";
}
private boolean containsDelete(final XmlElement element) {
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedGet extends AbstractConfigNetconfOperation {
+public class SimulatedGet extends AbstractLastNetconfOperation {
private final DataList storage;
public SimulatedGet(final String netconfSessionIdForReporting, final DataList storage) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
this.storage = storage;
}
import com.google.common.base.Optional;
import java.io.File;
import java.io.IOException;
-import java.util.Collections;
import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
-public class SimulatedGetConfig extends AbstractConfigNetconfOperation {
+public class SimulatedGetConfig extends AbstractLastNetconfOperation {
private final DataList storage;
private static final Logger LOG = LoggerFactory
public SimulatedGetConfig(final String netconfSessionIdForReporting, final DataList storage,
final Optional<File> initialConfigXMLFile) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
if (initialConfigXMLFile.isPresent()) {
LOG.info("File is present: {}", initialConfigXMLFile.get()
private static DataList loadInitialConfigXMLFile(final File file) {
LOG.info("Loading initial config xml file: {}", file.getName());
DataList configData = new DataList();
- List<XmlElement> xmlElementList = Collections.emptyList();
try {
Element element = XmlUtil.readXmlToElement(file);
XmlElement xmlElement = XmlElement.fromDomElement(element);
- xmlElementList = xmlElement.getChildElements();
+ List<XmlElement> xmlElementList = xmlElement.getChildElements();
configData.setConfigList(xmlElementList);
} catch (IOException e) {
LOG.info("IO exception loading xml file: {} ", e.getMessage());
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedLock extends AbstractConfigNetconfOperation {
+public class SimulatedLock extends AbstractLastNetconfOperation {
public SimulatedLock(final String netconfSessionIdForReporting) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
}
@Override
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
+import org.opendaylight.netconf.api.xml.XmlUtil;
+import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class SimulatedUnLock extends AbstractConfigNetconfOperation {
+public class SimulatedUnLock extends AbstractLastNetconfOperation {
public SimulatedUnLock(final String netconfSessionIdForReporting) {
- super(null, netconfSessionIdForReporting);
+ super(netconfSessionIdForReporting);
}
@Override
package org.opendaylight.netconf.test.tool.rpchandler;
import java.util.Optional;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.w3c.dom.Document;
public interface RpcHandler {
package org.opendaylight.netconf.test.tool.rpchandler;
import java.util.Optional;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationService;
package org.opendaylight.netconf.test.tool.rpchandler;
import java.util.Optional;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.netconf.mapping.api.HandlingPriority;
import org.opendaylight.netconf.mapping.api.NetconfOperation;
import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
package org.opendaylight.netconf.test.tool.scale.util;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.annotation.Arg;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
+@SuppressFBWarnings("DM_EXIT")
public class ScaleUtilParameters {
@Arg(dest = "distro-folder")
<configuration>
<instructions>
<Bundle-Name>YangLib</Bundle-Name>
- <Import-Package>*,
- com.sun.jersey.spi.container.servlet, org.eclipse.jetty.servlets</Import-Package>
+ <Import-Package>
+ com.sun.jersey.spi.container.servlet,
+ org.eclipse.jetty.servlets,
+ !javax.annotation,
+ javax.ws.rs.*;version="[1.1.0,2.0.0)",
+ *
+ </Import-Package>
<Web-ContextPath>/yanglib</Web-ContextPath>
</instructions>
</configuration>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
</plugins>
</build>
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
private final DataBroker dataBroker;
- private final YangLibServiceImpl yangLibService;
private final YanglibConfig yanglibConfig;
private SchemaListenerRegistration schemaListenerRegistration;
private SharedSchemaRepository schemaRepository;
- public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
- final YangLibServiceImpl yangLibService) {
+ public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker) {
this.yanglibConfig = Preconditions.checkNotNull(yanglibConfig);
this.dataBroker = Preconditions.checkNotNull(dataBroker);
- this.yangLibService = Preconditions.checkNotNull(yangLibService);
}
@Override
public void close() {
- yangLibService.setSchemaRepository(null);
+ YangLibServiceImpl.setSchemaRepository(null);
if (schemaListenerRegistration != null) {
schemaListenerRegistration.close();
}
schemaRepository.registerSchemaSourceListener(cache);
schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
- yangLibService.setSchemaRepository(schemaRepository);
+ YangLibServiceImpl.setSchemaRepository(schemaRepository);
LOG.info("Started yang library with sources from {}", cacheFolderFile);
}
return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString())))
.orElse(NO_REVISION);
}
-
- private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
- final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
- final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
- return (T) bundleContext.getService(serviceReference);
- }
}
import java.util.Set;
import javax.ws.rs.core.Application;
import org.opendaylight.yanglib.api.YangLibRestAppService;
-import org.osgi.framework.FrameworkUtil;
public class YangLibRestApp extends Application implements YangLibRestAppService {
-
- private final YangLibServiceImpl yangLibService;
-
- public YangLibRestApp() {
- this.yangLibService = new YangLibServiceImpl();
- FrameworkUtil.getBundle(getClass()).getBundleContext().registerService(YangLibRestAppService.class.getName(),
- this, null);
- }
+ private final YangLibServiceImpl yangLibService = new YangLibServiceImpl();
@Override
public Set<Object> getSingletons() {
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
+import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import org.opendaylight.yanglib.api.YangLibService;
import org.opendaylight.yangtools.yang.common.Revision;
public class YangLibServiceImpl implements YangLibService {
private static final Logger LOG = LoggerFactory.getLogger(YangLibServiceImpl.class);
- private volatile SchemaRepository schemaRepository;
+ private static volatile SchemaRepository schemaRepository;
public YangLibServiceImpl() {
}
- public void setSchemaRepository(final SchemaRepository schemaRepository) {
+ public static void setSchemaRepository(final SchemaRepository schemaRepository) {
LOG.debug("Setting schema repository {}", schemaRepository);
- this.schemaRepository = schemaRepository;
+ YangLibServiceImpl.schemaRepository = schemaRepository;
}
@Override
try {
final YangTextSchemaSource source = sourceFuture.get();
- return new String(ByteStreams.toByteArray(source.openStream()));
+ return new String(ByteStreams.toByteArray(source.openStream()), Charset.defaultCharset());
} catch (InterruptedException | ExecutionException | IOException e) {
throw new IllegalStateException("Unable to get schema " + sourceId, e);
}
<param-name>javax.ws.rs.Application</param-name>
<param-value>org.opendaylight.yanglib.impl.YangLibRestApp</param-value>
</init-param>
+ <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAXRSYanglib</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
-</web-app>
\ No newline at end of file
+</web-app>
binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig"/>
<reference id="dataBroker" interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
- <reference id="yangLibRestAppService" interface="org.opendaylight.yanglib.api.YangLibRestAppService"/>
<bean id="yangLibProvider" class="org.opendaylight.yanglib.impl.YangLibProvider"
init-method="init" destroy-method="close">
<argument ref="yanglibConfig"/>
<argument ref="dataBroker"/>
- <argument>
- <bean factory-ref="yangLibRestAppService" factory-method="getYangLibService"/>
- </argument>
</bean>
</blueprint>
final YanglibConfig yanglibConfig = new YanglibConfigBuilder().setBindingAddr("www.fake.com")
.setBindingPort(300L).setCacheFolder(CACHE_DIR.getAbsolutePath()).build();
- yangLibProvider = new YangLibProvider(yanglibConfig, dataBroker, new YangLibServiceImpl());
+ yangLibProvider = new YangLibProvider(yanglibConfig, dataBroker);
}
@Test
package org.opendaylight.yanglib.impl;
import static junit.framework.TestCase.assertTrue;
-import static org.mockito.BDDMockito.given;
-import static org.mockito.BDDMockito.then;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
import java.util.Set;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.opendaylight.yanglib.api.YangLibRestAppService;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(FrameworkUtil.class)
public class YangLibRestAppTest {
@Test
public void testYangLibRestApp() {
- PowerMockito.mockStatic(FrameworkUtil.class);
-
- final BundleContext bundleContext = mock(BundleContext.class);
- final Bundle bundle = mock(Bundle.class);
-
- given(FrameworkUtil.getBundle(any())).willReturn(bundle);
- given(bundle.getBundleContext()).willReturn(bundleContext);
-
final YangLibRestApp yangLibRestApp = new YangLibRestApp();
final Set singleton = yangLibRestApp.getSingletons();
assertTrue(singleton.contains(yangLibRestApp.getYangLibService()));
-
- then(bundleContext).should(times(1))
- .registerService(eq(YangLibRestAppService.class.getName()), eq(yangLibRestApp), eq(null));
}
}
*/
package org.opendaylight.protocol.framework;
+import com.google.common.base.Preconditions;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.Promise;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
/**
* Abstract base class for session negotiators. It implements the basic
* substrate to implement SessionNegotiator API specification, with subclasses
* @param <S> Protocol session type, has to extend {@code ProtocolSession<M>}
*/
@Deprecated
-public abstract class AbstractSessionNegotiator<M, S extends AbstractProtocolSession<?>> extends ChannelInboundHandlerAdapter implements SessionNegotiator<S> {
+public abstract class AbstractSessionNegotiator<M, S extends AbstractProtocolSession<?>>
+ extends ChannelInboundHandlerAdapter implements SessionNegotiator<S> {
private final Logger LOG = LoggerFactory.getLogger(AbstractSessionNegotiator.class);
private final Promise<S> promise;
protected final Channel channel;
* @param msg Message which should be sent.
*/
protected final void sendMessage(final M msg) {
- this.channel.writeAndFlush(msg).addListener(
- (ChannelFutureListener) f -> {
- if (!f.isSuccess()) {
- LOG.info("Failed to send message {}", msg, f.cause());
- negotiationFailed(f.cause());
- } else {
- LOG.trace("Message {} sent to socket", msg);
- }
- });
+ this.channel.writeAndFlush(msg).addListener(f -> {
+ if (!f.isSuccess()) {
+ LOG.info("Failed to send message {}", msg, f.cause());
+ negotiationFailed(f.cause());
+ } else {
+ LOG.trace("Message {} sent to socket", msg);
+ }
+ });
}
@Override
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.GenericFutureListener;
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
channel.pipeline().addLast(new ClosedChannelHandler(ReconnectPromise.this));
});
- pending.addListener((GenericFutureListener<Future<Object>>) future -> {
+ pending.addListener(future -> {
if (!future.isSuccess() && !ReconnectPromise.this.isDone()) {
ReconnectPromise.this.setFailure(future.cause());
}