<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependencyManagement>
<dependencies>
+ <dependency>
+ <groupId>org.opendaylight.mdsal.model</groupId>
+ <artifactId>mdsal-model-artifacts</artifactId>
+ <version>0.13.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>mdsal-artifacts</artifactId>
+ <version>1.8.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>netconf-artifacts</artifactId>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>odl-mdsal-broker</artifactId>
- <version>1.8.0-SNAPSHOT</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>odl-mdsal-models</artifactId>
- <version>0.13.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-mdsal-model-inventory</artifactId>
- <version>1.8.0-SNAPSHOT</version>
+ <artifactId>odl-mdsal-model-draft-clemm-netmod-yang-network-topo-01-minimal</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.netconf</groupId>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>2.0.7</version>
+ <version>2.0.9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>2.0.7</version>
+ <version>2.0.9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<classifier>features</classifier>
</dependency>
<dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>odl-mdsal-models</artifactId>
+ <groupId>org.opendaylight.netconf</groupId>
+ <artifactId>odl-protocol-framework</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<dependency>
- <groupId>org.opendaylight.netconf</groupId>
- <artifactId>odl-protocol-framework</artifactId>
+ <groupId>org.opendaylight.mdsal.model</groupId>
+ <artifactId>odl-mdsal-model-rfc7895</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
+
+
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>netconf-api</artifactId>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>ietf-netconf-monitoring-extension</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>rfc7895</artifactId>
- </dependency>
</dependencies>
</project>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="odl-netconf-${project.version}">
<feature name="odl-netconf-api" version="${project.version}">
- <feature version="[2.0.7,3)">odl-yangtools-parser-api</feature>
+ <feature version="[2.0.9,3)">odl-yangtools-parser-api</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>com.siemens.ct.exi</groupId>
<artifactId>exificient</artifactId>
- <version>0.9.7</version>
+ <version>1.0.1</version>
</dependency>
</dependencies>
</project>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>odl-yangtools-codec</artifactId>
- <version>2.0.7</version>
+ <version>2.0.9</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<configfile finalname="etc/netconf.cfg">
mvn:org.opendaylight.netconf/netconf-util/${project.version}/cfg/config
</configfile>
- <feature version="[2.0.7,3)">odl-yangtools-codec</feature>
+ <feature version="[2.0.9,3)">odl-yangtools-codec</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odl-jackson-2.8</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependencyManagement>
<dependencies>
+ <dependency>
+ <groupId>org.opendaylight.mdsal.model</groupId>
+ <artifactId>mdsal-model-artifacts</artifactId>
+ <version>0.13.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>restconf-artifacts</artifactId>
</dependencyManagement>
<dependencies>
+ <dependency>
+ <groupId>org.opendaylight.mdsal.model</groupId>
+ <artifactId>odl-mdsal-model-draft-bierman-netconf-restconf-02</artifactId>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>odl-restconf-common</artifactId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>2.0.7</version>
+ <version>2.0.9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>odl-mdsal-models</artifactId>
+ <artifactId>odl-mdsal-model-rfc7895</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odl-jackson-2.8</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<feature name="odl-restconf-common" version="${project.version}">
<feature version="[3.1.0,4)">odl-karaf-feat-jetty</feature>
<feature version="[3.1.0,4)">odl-jackson-2.8</feature>
- <feature version="[2.0.7,3)">odl-yangtools-export</feature>
+ <feature version="[2.0.9,3)">odl-yangtools-export</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<type>pom</type>
<scope>import</scope>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.netconf</groupId>
+ <artifactId>netconf-artifacts</artifactId>
+ <version>1.5.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
</dependencies>
</dependencyManagement>
<type>xml</type>
<classifier>features</classifier>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.netconf</groupId>
+ <artifactId>odl-netconf-api</artifactId>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>restconf-nb-rfc8040</artifactId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<artifactId>features-restconf-aggregator</artifactId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<name>OpenDaylight :: Yanglib</name>
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.netconf</groupId>
+ <artifactId>netconf-artifacts</artifactId>
+ <version>1.5.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.netconf</groupId>
+ <artifactId>restconf-artifacts</artifactId>
+ <version>1.8.0-SNAPSHOT</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
<dependencies>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>yanglib</artifactId>
- <version>1.5.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>odl-restconf</artifactId>
- <version>1.8.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal.model</groupId>
- <artifactId>odl-mdsal-models</artifactId>
- <version>0.13.0-SNAPSHOT</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>karaf4-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.netconf</groupId>
@Override
protected void applyTo(final ClientSession session) {
Preconditions.checkArgument(session instanceof ClientSessionImpl);
- ((ClientSessionImpl) session).setUsername(username);
+ session.setUsername(username);
// First try authentication using server host keys, else try password.
for (KeyPair keyPair : clientKeyPair) {
private ChannelOutboundHandlerAdapter createChannelAdapter() {
return new ChannelOutboundHandlerAdapter() {
@Override
- public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
- throws Exception {
+ public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
sshWriteAsyncHandler.write(ctx, msg, promise);
}
};
}
@Override
- protected void doBind(final SocketAddress localAddress) throws Exception {
+ protected void doBind(final SocketAddress localAddress) {
throw new UnsupportedOperationException("Bind not supported.");
}
}
@Override
- protected void doDisconnect() throws Exception {
+ protected void doDisconnect() {
LOG.info("Disconnect invoked");
doNettyDisconnect();
doMinaDisconnect(false);
}
@Override
- protected void doClose() throws Exception {
+ protected void doClose() {
context.removeSelf();
if (notClosing(session)) {
session.close(true);
}
@Override
- protected void doBeginRead() throws Exception {
+ protected void doBeginRead() {
// Intentional NOOP - read is started by AsyncSshHandlerReader
}
@Override
- protected void doWrite(final ChannelOutboundBuffer in) throws Exception {
+ protected void doWrite(final ChannelOutboundBuffer in) {
throw new IllegalStateException("Outbound writes to SSH should be done by SSH Write handler");
}
* Invoked when SSH session dropped during read using {@link AsyncSshHandlerReader}.
*/
@Override
- public void close() throws Exception {
+ public void close() {
doNettyDisconnect();
}
}
}
@Override
- public void close() throws Exception {
+ public void close() {
acceptor.close(true);
}
}
}
@Override
- public void close() throws Exception {
+ public void close() {
configReg.close();
deviceReg.close();
deviceOpReg.close();
}
@Override
- public void close() throws Exception {
+ public void close() {
reg.close();
}
}
}
@Override
- public void close() throws Exception {
+ public void close() {
authProvider.close();
statusReporter.close();
}
@Override
- public void close() throws Exception {
+ public void close() {
listeners1.clear();
schemaContextListenerListenerRegistration.close();
currentContext.set(null);
this.dataBroker = dataBroker;
this.rpcService = rpcService;
- this.rootSchemaSourceProviderDependency = (DOMYangTextSourceProvider) schemaService.getSupportedExtensions()
- .get(DOMYangTextSourceProvider.class);
+ this.rootSchemaSourceProviderDependency = schemaService.getExtensions()
+ .getInstance(DOMYangTextSourceProvider.class);
this.currentSchemaContext = new CurrentSchemaContext(Preconditions.checkNotNull(schemaService),
rootSchemaSourceProviderDependency);
this.netconfOperationServiceFactoryListener = netconfOperationServiceFactoryListener;
}
@Override
- public synchronized void close() throws Exception {
+ public synchronized void close() {
for (final DOMDataReadWriteTransaction rwt : allOpenReadWriteTransactions) {
rwt.cancel();
}
netconfSessionIdForReporting, e);
final String cause = e.getCause() != null ? (" Cause: " + e.getCause().getMessage()) : "";
throw new DocumentedException(
- "Candidate transaction validate failed on " + e.getMessage() + " " + netconfSessionIdForReporting
- + cause, e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
+ "Candidate transaction validate failed [sessionId=" + netconfSessionIdForReporting + "]: "
+ + e.getMessage() + cause,
+ e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
}
- return;
}
public synchronized boolean commitTransaction() throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Locking candidate datastore on session: {}", getNetconfSessionIdForReporting());
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
throw new DocumentedException("Unable to lock " + targetDatastore + " datastore",
final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Unlocking candidate datastore on session: {}", getNetconfSessionIdForReporting());
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
throw new DocumentedException("Unable to unlock " + targetDatastore + " datastore",
return sourceElement.isPresent()
? Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName()))
- : Optional.<Datastore>absent();
+ : Optional.absent();
}
private static void validateInputRpc(final XmlElement xml, final String operationName) throws
final Optional<YangInstanceIdentifier> dataRootOptional = getDataRootFromFilter(operationElement);
if (!dataRootOptional.isPresent()) {
- return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
}
final YangInstanceIdentifier dataRoot = dataRootOptional.get();
transactionProvider.abortRunningTransaction(rwTx);
if (!normalizedNodeOptional.isPresent()) {
- return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
}
return serializeNodeWithParentStructure(document, dataRoot, normalizedNodeOptional.get());
final Optional<YangInstanceIdentifier> dataRootOptional = getDataRootFromFilter(operationElement);
if (!dataRootOptional.isPresent()) {
- return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
}
final YangInstanceIdentifier dataRoot = dataRootOptional.get();
}
if (!normalizedNodeOptional.isPresent()) {
- return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
}
return serializeNodeWithParentStructure(document, dataRoot, normalizedNodeOptional.get());
*/
package org.opendaylight.netconf.mdsal.connector.ops;
+import com.google.common.collect.ClassToInstanceMap;
+import com.google.common.collect.ImmutableClassToInstanceMap;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
+import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
}
};
}
+
+ @Override
+ public ClassToInstanceMap<DOMSchemaServiceExtension> getExtensions() {
+ return ImmutableClassToInstanceMap.of();
+ }
}
netconfCapabilityChangeBuilder.setAddedCapability(ImmutableList.copyOf(added));
netconfCapabilityChangeBuilder.setDeletedCapability(ImmutableList.copyOf(removed));
// TODO modified should be computed ... but why ?
- netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
+ netconfCapabilityChangeBuilder.setModifiedCapability(Collections.emptyList());
baseNotificationPublisherRegistration.onCapabilityChanged(netconfCapabilityChangeBuilder.build());
}
Map<InstanceIdentifier<?>, DataObject> createdData = Maps.newHashMap();
createdData.put(capabilitiesIdentifier, newCapabilities);
verifyDataTreeChange(DataObjectModification.ModificationType.WRITE, null, newCapabilities,
- changedCapabilitesFrom(newCapabilitiesList, Collections.<Uri>emptyList()));
+ changedCapabilitesFrom(newCapabilitiesList, Collections.emptyList()));
}
@Test
netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(
new ServerBuilder().setServer(true).build()).build());
- netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
+ netconfCapabilityChangeBuilder.setModifiedCapability(Collections.emptyList());
netconfCapabilityChangeBuilder.setAddedCapability(added);
netconfCapabilityChangeBuilder.setDeletedCapability(deleted);
import org.mockito.MockitoAnnotations;
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.DataObjectModification.ModificationType;
import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.netconf.notifications.BaseNotificationPublisherRegistration;
import org.opendaylight.netconf.notifications.NetconfNotificationCollector;
-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.HostBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
@Test
public void testOnDataChangedSessionCreated() throws Exception {
final Session session = createSession(1);
- final DataTreeModification<Session> treeChange = getTreeModification(session, DataObjectModification
- .ModificationType.WRITE);
+ final DataTreeModification<Session> treeChange = getTreeModification(session, ModificationType.WRITE);
publisher.onDataTreeChanged(Collections.singleton(treeChange));
ArgumentCaptor<NetconfSessionStart> captor = ArgumentCaptor.forClass(NetconfSessionStart.class);
verify(registration).onSessionStarted(captor.capture());
final Session sessionAfter = createSessionWithInRpcCount(1, 1);
doReturn(sessionBefore).when(changeObject).getDataBefore();
doReturn(sessionAfter).when(changeObject).getDataAfter();
- doReturn(DataObjectModification.ModificationType.WRITE).when(changeObject).getModificationType();
+ doReturn(ModificationType.WRITE).when(changeObject).getModificationType();
doReturn(changeObject).when(treeChange).getRootNode();
publisher.onDataTreeChanged(Collections.singleton(treeChange));
//session didn't start, only stats changed. No notification should be produced
@Test
public void testOnDataChangedSessionDeleted() throws Exception {
final Session session = createSession(1);
- final DataTreeModification<Session> data = getTreeModification(session, DataObjectModification
- .ModificationType.DELETE);
+ final DataTreeModification<Session> data = getTreeModification(session, ModificationType.DELETE);
publisher.onDataTreeChanged(Collections.singleton(data));
ArgumentCaptor<NetconfSessionEnd> captor = ArgumentCaptor.forClass(NetconfSessionEnd.class);
verify(registration).onSessionEnded(captor.capture());
Assert.assertEquals(session.getUsername(), value.getUsername());
}
- private Session createSession(long id) {
+ private static Session createSession(long id) {
return createSessionWithInRpcCount(id, 0);
}
- private Session createSessionWithInRpcCount(long id, long inRpc) {
+ private static Session createSessionWithInRpcCount(long id, long inRpc) {
return new SessionBuilder()
.setSessionId(id)
- .setSourceHost(new Host("0.0.0.0".toCharArray()))
+ .setSourceHost(HostBuilder.getDefaultInstance("0.0.0.0"))
.setUsername("user")
.setInRpcs(new ZeroBasedCounter32(inRpc))
.build();
}
@SuppressWarnings("unchecked")
- private DataTreeModification<Session> getTreeModification(Session session, DataObjectModification
- .ModificationType type) {
+ private static DataTreeModification<Session> getTreeModification(Session session, ModificationType type) {
final DataTreeModification<Session> treeChange = mock(DataTreeModification.class);
final DataObjectModification<Session> changeObject = mock(DataObjectModification.class);
switch (type) {
}
@Override
- public void close() throws Exception {
+ public void close() {
// TODO Delete modules-state from operational data store
}
}
@Override
- public void close() throws Exception {
+ public void close() {
closeStream();
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ this(message, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
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());
+ this(message, cause, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Set;
-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;
private final NetconfHelloMessageAdditionalHeader additionalHeader;
- public NetconfHelloMessage(final Document doc, final NetconfHelloMessageAdditionalHeader additionalHeader)
- throws NetconfDocumentedException {
+ public NetconfHelloMessage(final Document doc, final NetconfHelloMessageAdditionalHeader additionalHeader) {
super(doc);
checkHelloMessage(doc);
this.additionalHeader = additionalHeader;
}
- public NetconfHelloMessage(final Document doc) throws NetconfDocumentedException {
+ public NetconfHelloMessage(final Document doc) {
this(doc, null);
}
}
public static NetconfHelloMessage createClientHello(final Iterable<String> capabilities,
- final Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional)
- throws NetconfDocumentedException {
+ final Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) {
return new NetconfHelloMessage(createHelloMessageDoc(capabilities), additionalHeaderOptional.orNull());
}
return doc;
}
- public static NetconfHelloMessage createServerHello(final Set<String> capabilities, final long sessionId)
- throws NetconfDocumentedException {
+ public static NetconfHelloMessage createServerHello(final Set<String> capabilities, final long sessionId) {
Document doc = createHelloMessageDoc(capabilities);
Element sessionIdElement = doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
XmlNetconfConstants.SESSION_ID);
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());
+ this(message, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType,
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());
+ this(message, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType,
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());
+ this(message, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType,
}
public void checkUnrecognisedElements(final XmlElement... additionalRecognisedElements) throws DocumentedException {
- checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
+ checkUnrecognisedElements(Collections.emptyList(), additionalRecognisedElements);
}
@Override
final String prefix, final String namespace, final String contentWithoutPrefix) {
return createTextElementWithNamespacedContent(document, qname, prefix, namespace, contentWithoutPrefix,
- Optional.<String>absent());
+ Optional.absent());
}
public static Element createTextElementWithNamespacedContent(final Document document, final String qname,
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
@Override
protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
- final NetconfHelloMessage message) throws NetconfDocumentedException {
+ final NetconfHelloMessage message) {
final long sessionId = extractSessionId(message.getDocument());
// Copy here is important: it disconnects the strings from the document
* 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.client;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
-import com.siemens.ct.exi.CodingMode;
-import com.siemens.ct.exi.FidelityOptions;
-import com.siemens.ct.exi.exceptions.UnsupportedOption;
+import com.siemens.ct.exi.core.CodingMode;
+import com.siemens.ct.exi.core.FidelityOptions;
+import com.siemens.ct.exi.core.exceptions.UnsupportedOption;
import io.netty.channel.Channel;
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
import java.util.Set;
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;
private static final String START_EXI_MESSAGE_ID = "default-start-exi";
private static final EXIParameters DEFAULT_OPTIONS;
- private final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader;
- private final long connectionTimeoutMillis;
- private final Timer timer;
- private final EXIParameters options;
-
static {
final FidelityOptions fidelity = FidelityOptions.createDefault();
try {
DEFAULT_OPTIONS = new EXIParameters(CodingMode.BYTE_PACKED, fidelity);
}
+ private final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader;
private final Set<String> clientCapabilities;
+ private final long connectionTimeoutMillis;
+ private final Timer timer;
+ private final EXIParameters options;
public NetconfClientSessionNegotiatorFactory(final Timer timer,
final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
final long connectionTimeoutMillis, final EXIParameters exiOptions,
final Set<String> capabilities) {
- this.timer = Preconditions.checkNotNull(timer);
+ this.timer = requireNonNull(timer);
this.additionalHeader = additionalHeader;
this.connectionTimeoutMillis = connectionTimeoutMillis;
this.options = exiOptions;
final Channel channel, final Promise<NetconfClientSession> promise) {
NetconfMessage startExiMessage = NetconfStartExiMessage.create(options, START_EXI_MESSAGE_ID);
- NetconfHelloMessage helloMessage = null;
- try {
- helloMessage = NetconfHelloMessage.createClientHello(clientCapabilities, additionalHeader);
- } catch (NetconfDocumentedException e) {
- LOG.error("Unable to create client hello message with capabilities {} and additional handler {}",
- clientCapabilities, additionalHeader);
- throw new IllegalStateException(e);
- }
+ NetconfHelloMessage helloMessage = NetconfHelloMessage.createClientHello(clientCapabilities, additionalHeader);
NetconfClientSessionPreferences proposal = new NetconfClientSessionPreferences(helloMessage, startExiMessage);
return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
}
public final synchronized Future<NetconfMessage> sendRequest(NetconfMessage message) {
- final RequestEntry req = new RequestEntry(GlobalEventExecutor.INSTANCE.<NetconfMessage>newPromise(), message);
+ final RequestEntry req = new RequestEntry(GlobalEventExecutor.INSTANCE.newPromise(), message);
requests.add(req);
if (clientSession != null) {
import io.netty.channel.Channel;
import io.netty.util.concurrent.Promise;
-import java.io.IOException;
import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
- try {
- // ssh handler has to be the first handler in pipeline
- ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(authenticationHandler, promise));
- super.initialize(ch, promise);
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
+ // ssh handler has to be the first handler in pipeline
+ ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(authenticationHandler, promise));
+ super.initialize(ch, promise);
}
@Override
@Override
public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
final SocketAddress localAddress,
- final ChannelPromise channelPromise) throws Exception {
+ final ChannelPromise channelPromise) {
connectPromise = channelPromise;
ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);
}
@Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ public void channelActive(ChannelHandlerContext ctx) {
ctx.pipeline().replace(this, "sslHandler", sslHandlerFactory.createSslHandler())
.fireChannelActive();
}
import io.netty.util.Timer;
import io.netty.util.concurrent.Promise;
import org.junit.Test;
-import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
Channel channel = mock(Channel.class);
Promise<NetconfClientSession> promise = mock(Promise.class);
NetconfClientSessionNegotiatorFactory negotiatorFactory = new NetconfClientSessionNegotiatorFactory(timer,
- Optional.<NetconfHelloMessageAdditionalHeader>absent(), 200L);
+ Optional.absent(), 200L);
SessionNegotiator<?> sessionNegotiator = negotiatorFactory.getSessionNegotiator(listenerFactory, channel,
promise);
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.util.concurrent.Promise;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-test-util</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-binding-broker-impl</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-binding-broker-impl</artifactId>
<scope>test</scope>
- </dependency>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
package org.opendaylight.netconf.console.commands;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import java.util.Arrays;
this.devicePort = devicePort;
}
+ @VisibleForTesting
+ NetconfConnectDeviceCommand(final NetconfCommands service, final String deviceIp, final String devicePort,
+ final String username, final String password) {
+ this.service = requireNonNull(service);
+ this.deviceIp = requireNonNull(deviceIp);
+ this.devicePort = requireNonNull(devicePort);
+ this.username = requireNonNull(username);
+ this.password = requireNonNull(password);
+ }
+
@Option(name = "-i",
aliases = { "--ipaddress" },
description = "IP address of the netconf device",
return topology != null && topology.getNode() != null && !topology.getNode().isEmpty();
}
- /**
- * Wait for datastore to populate NETCONF data.
- * @param deviceIp :IP address of NETCONF device
- */
- public static void waitForUpdate(final String deviceIp) {
- try {
- Thread.sleep(NetconfConsoleConstants.DEFAULT_TIMEOUT_MILLIS);
- } catch (final InterruptedException e) {
- LOG.warn("Interrupted while waiting after Netconf node {}", deviceIp, e);
- }
- }
-
/**
* Blocking read transaction.
* @param store :DatastoreType
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.Arrays;
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.execute();
verify(netconfCommands, times(0)).connectDevice(any(), any());
- netconfConnectDeviceCommand = new NetconfConnectDeviceCommand(netconfCommands, "192.168.1.1", "7777");
+ netconfConnectDeviceCommand = new NetconfConnectDeviceCommand(netconfCommands, "192.168.1.1", "7777", "user",
+ "pass");
- PowerMockito.mockStatic(Strings.class);
- given(Strings.isNullOrEmpty(any())).willReturn(false);
netconfConnectDeviceCommand.execute();
doNothing().when(netconfCommands).connectDevice(any(), any());
verify(netconfCommands, times(1)).connectDevice(any(), any());
private static HashMap<String, Map<String, List<String>>> getDeviceHashMap() {
final HashMap<String, Map<String, List<String>>> devices = new HashMap<>();
final HashMap<String, List<String>> deviceMap = new HashMap<>();
- deviceMap.put(NetconfConsoleConstants.NETCONF_IP, Lists.newArrayList("192.168.1.1"));
- deviceMap.put(NetconfConsoleConstants.NETCONF_PORT, Lists.newArrayList("7777"));
- deviceMap.put(NetconfConsoleConstants.STATUS, Lists.newArrayList("connecting"));
- deviceMap.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES, Lists.newArrayList("cap1", "cap2", "cap3"));
+ deviceMap.put(NetconfConsoleConstants.NETCONF_IP, Arrays.asList("192.168.1.1"));
+ deviceMap.put(NetconfConsoleConstants.NETCONF_PORT, Arrays.asList("7777"));
+ deviceMap.put(NetconfConsoleConstants.STATUS, Arrays.asList("connecting"));
+ deviceMap.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES, Arrays.asList("cap1", "cap2", "cap3"));
devices.put("device", deviceMap);
return devices;
}
import static org.junit.Assert.assertNotNull;
import com.google.common.collect.ImmutableList;
-import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
-import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import javassist.ClassPool;
+import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+import org.opendaylight.controller.md.sal.binding.test.ConcurrentDataBrokerTestCustomizer;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-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.spi.data.DOMStore;
-import org.opendaylight.mdsal.binding.dom.codec.gen.impl.DataObjectSerializerGenerator;
-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.GeneratedClassLoadingStrategy;
-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.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
import org.opendaylight.netconf.console.utils.NetconfIidFactory;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
-import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class NetconfCommandsImplTest {
"/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang",
"/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang");
schemaContext.getModules();
- final DOMSchemaService schemaService = createSchemaService();
- final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
- final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
-
- final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
- datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
- datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
-
- final DOMDataBroker domDataBroker =
- new SerializedDOMDataBroker(datastores, MoreExecutors.newDirectExecutorService());
-
- final ClassPool pool = ClassPool.getDefault();
- final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
- final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
- final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- codecRegistry
- .onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
-
- final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
- final BindingToNormalizedNodeCodec bindingToNormalized =
- new BindingToNormalizedNodeCodec(loading, codecRegistry);
- bindingToNormalized.onGlobalContextUpdated(schemaContext);
- dataBroker = new BindingDOMDataBrokerAdapter(domDataBroker, bindingToNormalized);
+ ConcurrentDataBrokerTestCustomizer customizer = new ConcurrentDataBrokerTestCustomizer(true);
+ dataBroker = customizer.createDataBroker();
+ customizer.updateSchema(schemaContext);
netconfCommands = new NetconfCommandsImpl(dataBroker);
}
createTopology(LogicalDatastoreType.CONFIGURATION);
netconfCommands.connectDevice(netconfNode, "netconf-ID");
- NetconfConsoleUtils.waitForUpdate("10.10.1.1");
- final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
- NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
- final List<Node> nodes = topology.getNode();
- assertEquals(2, nodes.size());
+ Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> {
+ final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
+ NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
+ final List<Node> nodes = topology.getNode();
+ if (nodes.size() != 2) {
+ return false;
+ }
- final Optional<Node> storedNode = nodes.stream().filter(node ->
- node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
+ final Optional<Node> storedNode = nodes.stream().filter(node ->
+ node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
- assertTrue(storedNode.isPresent());
+ assertTrue(storedNode.isPresent());
- NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
- assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
- assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+ NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
+ assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
+ assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+ return true;
+ });
netconfCommands.disconnectDevice("netconf-ID");
- final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
- NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
- final List<Node> nodesDeleted = topologyDeleted.getNode();
- assertEquals(1, nodesDeleted.size());
+ Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> {
+ final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
+ NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
+ final List<Node> nodesDeleted = topologyDeleted.getNode();
+ if (nodesDeleted.size() != 1) {
+ return false;
+ }
- final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
- node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
+ final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
+ node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
- assertFalse(storedNodeDeleted.isPresent());
+ assertFalse(storedNodeDeleted.isPresent());
+ return true;
+ });
}
@Test
update.put(NetconfConsoleConstants.SCHEMALESS, "true");
netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
- NetconfConsoleUtils.waitForUpdate("7.7.7.7");
- final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
- NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
- final List<Node> nodes = topology.getNode();
- assertEquals(1, nodes.size());
+ Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> {
+ final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
+ NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
+ final List<Node> nodes = topology.getNode();
+ if (nodes.size() != 1) {
+ return false;
+ }
- final Optional<Node> storedNode = nodes.stream().filter(node ->
- node.key().getNodeId().getValue().equals(NODE_ID)).findFirst();
- assertTrue(storedNode.isPresent());
+ final Optional<Node> storedNode = nodes.stream().filter(node ->
+ node.key().getNodeId().getValue().equals(NODE_ID)).findFirst();
+ assertTrue(storedNode.isPresent());
- NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
- assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+ NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
+ assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+ return true;
+ });
}
@Test
assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
}
-
- private DOMSchemaService createSchemaService() {
- return new DOMSchemaService() {
-
- @Override
- public SchemaContext getSessionContext() {
- return schemaContext;
- }
-
- @Override
- public SchemaContext getGlobalContext() {
- return schemaContext;
- }
-
- @Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
- final SchemaContextListener listener) {
- listener.onGlobalContextUpdated(getGlobalContext());
- return new AbstractListenerRegistration<SchemaContextListener>(listener) {
-
- @Override
- protected void removeRegistration() {
- // No-op
- }
- };
- }
- };
- }
}
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
-import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalServerChannel;
-import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.Promise;
import java.net.InetSocketAddress;
import org.opendaylight.netconf.api.NetconfServerDispatcher;
@Override
public ChannelFuture createServer(InetSocketAddress address) {
- return super.createServer(address, new PipelineInitializer<NetconfServerSession>() {
- @Override
- public void initializeChannel(final SocketChannel ch, final Promise<NetconfServerSession> promise) {
- initializer.initialize(ch, promise);
- }
- });
+ return super.createServer(address, initializer::initialize);
}
@Override
public ChannelFuture createLocalServer(LocalAddress address) {
- return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel,
- NetconfServerSession>() {
- @Override
- public void initializeChannel(final LocalChannel ch, final Promise<NetconfServerSession> promise) {
- initializer.initialize(ch, promise);
- }
- });
+ return super.createServer(address, LocalServerChannel.class, initializer::initialize);
}
public static class ServerChannelInitializer extends AbstractChannelInitializer<NetconfServerSession> {
import io.netty.util.concurrent.Promise;
import java.net.SocketAddress;
import java.util.Set;
-import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.NetconfServerSessionPreferences;
import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
final Channel channel, final Promise<NetconfServerSession> promise) {
final long sessionId = idProvider.getNextSessionId();
- NetconfServerSessionPreferences proposal;
- try {
- proposal = new NetconfServerSessionPreferences(createHelloMessage(sessionId, monitoringService), sessionId);
- } catch (final NetconfDocumentedException e) {
- LOG.error("Unable to create hello message for session {} with {}", sessionId, monitoringService);
- throw new IllegalStateException(e);
- }
+ NetconfServerSessionPreferences proposal =
+ new NetconfServerSessionPreferences(createHelloMessage(sessionId, monitoringService), sessionId);
return new NetconfServerSessionNegotiator(proposal, promise, channel, timer,
getListener(Long.toString(sessionId), channel.parent().localAddress()), connectionTimeoutMillis);
}
private NetconfHelloMessage createHelloMessage(
- final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
+ final long sessionId, final NetconfMonitoringService capabilityProvider) {
return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider
.getCapabilities()), baseCapabilities), sessionId);
}
DocumentedException.ErrorSeverity.ERROR, Collections.singletonMap(
DocumentedException.ErrorSeverity.ERROR.toString(), e.getMessage()));
}
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
@Override
@Override
protected Element handleWithNoSubsequentOperations(final Document document,
- final XmlElement operationElement) throws DocumentedException {
+ final XmlElement operationElement) {
final Element getSchemaResult = document.createElementNS(
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
LOG.trace("{} operation successful", START_EXI);
*/
package org.opendaylight.netconf.impl.mapping.operations;
-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;
@Override
protected Element handleWithNoSubsequentOperations(Document document,
- XmlElement operationElement) throws DocumentedException {
+ XmlElement operationElement) {
LOG.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
netconfSession.stopExiCommunication();
}
final String currentModuleName = cap.getModuleName().get();
- Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
- if (revisionMap == null) {
- revisionMap = Maps.newHashMap();
- mappedModulesToRevisionToSchema.put(currentModuleName, revisionMap);
- }
+ Map<String, String> revisionMap =
+ mappedModulesToRevisionToSchema.computeIfAbsent(currentModuleName, k -> Maps.newHashMap());
final String currentRevision = cap.getRevision().get();
revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
}
@Override
- public synchronized void close() throws Exception {
+ public synchronized void close() {
listeners.clear();
capabilities.clear();
}
netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2
.transform(added, CAPABILITY_TO_URI)));
// TODO modified should be computed ... but why ?
- netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
+ netconfCapabilityChangeBuilder.setModifiedCapability(Collections.emptyList());
return netconfCapabilityChangeBuilder.build();
}
}
@Override
- public void close() throws Exception {
+ public void close() {
capabilityMonitoring.close();
sessionMonitoring.close();
}
}
@Override
- public void close() throws Exception {
+ public void close() {
netconfOperationServiceSnapshot.close();
}
- private static DocumentedException handleUnexpectedEx(final String message, final Exception exception) throws
- DocumentedException {
+ private static DocumentedException handleUnexpectedEx(final String message, final Exception exception) {
LOG.error("{}", message, exception);
return new DocumentedException("Unexpected error",
DocumentedException.ErrorType.APPLICATION,
if (!running) {
startUpdateSessionStats();
}
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- listeners.remove(listener);
- }
- };
+ return () -> listeners.remove(listener);
}
@Override
- public synchronized void close() throws Exception {
+ public synchronized void close() {
stopUpdateSessionStats();
listeners.clear();
sessions.clear();
private static final Logger LOG = LoggerFactory.getLogger(DeserializerExceptionHandler.class);
@Override
- public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
+ public void handlerAdded(final ChannelHandlerContext ctx) {
// NOOP
}
@Override
- public void handlerRemoved(final ChannelHandlerContext ctx) throws Exception {
+ public void handlerRemoved(final ChannelHandlerContext ctx) {
// NOOP
}
@Override
- public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
+ public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
LOG.warn("An exception occurred during message handling", cause);
handleDeserializerException(ctx, cause);
}
import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
import org.opendaylight.netconf.util.test.XmlFileLoader;
import org.opendaylight.protocol.framework.NeverReconnectStrategy;
-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.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
doReturn(sessionListener).when(monitoring).getSessionListener();
- doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring)
+ doReturn(new CapabilitiesBuilder().setCapability(Collections.emptyList()).build()).when(monitoring)
.getCapabilities();
return monitoring;
}
}
assertTrue(messages.isEmpty());
- NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
+ NetconfMessage receivedMessage = testChunkChannel.readInbound();
assertNotNull(receivedMessage);
assertXMLEqual(this.msg.getDocument(), receivedMessage.getDocument());
}
new NetconfMessageToXMLEncoder(), new NetconfEOMAggregator(), new NetconfXMLToMessageDecoder());
testChunkChannel.writeOutbound(this.msg);
- ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();
+ ByteBuf recievedOutbound = testChunkChannel.readOutbound();
byte[] endOfMsgBytes = NetconfMessageConstants.END_OF_MESSAGE.getBytes(StandardCharsets.UTF_8);
byte[] eom = new byte[endOfMsgBytes.length];
assertArrayEquals(endOfMsgBytes, eom);
testChunkChannel.writeInbound(recievedOutbound);
- NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
+ NetconfMessage receivedMessage = testChunkChannel.readInbound();
assertNotNull(receivedMessage);
assertXMLEqual(this.msg.getDocument(), receivedMessage.getDocument());
}
listener.onMessage(session, msg);
verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_SUCCESS)));
channel.runPendingTasks();
- final NetconfMessage sentMsg = (NetconfMessage) channel.readOutbound();
+ final NetconfMessage sentMsg = channel.readOutbound();
final Diff diff = XMLUnit.compareXML(reply, sentMsg.getDocument());
Assert.assertTrue(diff.toString(), diff.similar());
}
verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_FAIL)));
verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.OUT_RPC_ERROR)));
channel.runPendingTasks();
- final NetconfMessage sentMsg = (NetconfMessage) channel.readOutbound();
+ final NetconfMessage sentMsg = channel.readOutbound();
System.out.println(XmlUtil.toString(sentMsg.getDocument()));
System.out.println(XmlUtil.toString(reply));
final Diff diff = XMLUnit.compareXML(reply, sentMsg.getDocument());
final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header);
tcpSession.sessionUp();
final Session managementSession = tcpSession.toManagementSession();
- Assert.assertEquals(new String(managementSession.getSourceHost().getValue()), HOST);
+ Assert.assertEquals(HOST, managementSession.getSourceHost().getIpAddress().getIpv4Address().getValue());
Assert.assertEquals(managementSession.getUsername(), USER);
Assert.assertEquals(managementSession.getSessionId().toString(), SESSION_ID);
Assert.assertEquals(managementSession.getTransport(), NetconfTcp.class);
final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header);
tcpSession.sessionUp();
tcpSession.toManagementSession();
+ tcpSession.close();
}
@Test
final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header);
tcpSession.sessionUp();
final Session managementSession = tcpSession.toManagementSession();
- Assert.assertEquals(new String(managementSession.getSourceHost().getValue()), "::1");
+ Assert.assertEquals("::1", managementSession.getSourceHost().getIpAddress().getIpv6Address().getValue());
Assert.assertEquals(managementSession.getUsername(), USER);
Assert.assertEquals(managementSession.getSessionId().toString(), SESSION_ID);
Assert.assertEquals(managementSession.getTransport(), NetconfSsh.class);
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.netconf.notifications.BaseNotificationPublisherRegistration;
-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.HostBuilder;
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.monitoring.rev101004.netconf.state.Capabilities;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
private YangModuleCapability moduleCapability2;
private static final Session SESSION = new SessionBuilder()
.setSessionId(1L)
- .setSourceHost(new Host("0.0.0.0".toCharArray()))
+ .setSourceHost(HostBuilder.getDefaultInstance("0.0.0.0"))
.setUsername("admin")
.build();
private int capabilitiesSize;
import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.netconf.api.monitoring.SessionEvent;
import org.opendaylight.netconf.notifications.BaseNotificationPublisherRegistration;
-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.HostBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionBuilder;
private static final Session SESSION_1 = new SessionBuilder()
.setSessionId(1L)
- .setSourceHost(new Host("0.0.0.0".toCharArray()))
+ .setSourceHost(HostBuilder.getDefaultInstance("0.0.0.0"))
.setUsername("admin")
.build();
private static final Session SESSION_2 = new SessionBuilder()
.setSessionId(2L)
- .setSourceHost(new Host("0.0.0.0".toCharArray()))
+ .setSourceHost(HostBuilder.getDefaultInstance("0.0.0.0"))
.setUsername("admin")
.build();
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<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-subsystem</artifactId>
- <version>1.5.0-SNAPSHOT</version>
- </parent>
-
- <artifactId>netconf-it</artifactId>
- <name>${project.artifactId}</name>
- <packaging>jar</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-netty-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
- <!-- compile dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>sal-netconf-connector</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-api</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-client</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-client</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-mapping-api</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-monitoring</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-netty-util</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-ssh</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-testtool</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-ssh</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </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>netty-config-api</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</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.it;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import com.google.common.base.Throwables;
-import com.google.common.io.ByteStreams;
-import com.google.common.util.concurrent.CheckedFuture;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.local.LocalAddress;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
-import io.netty.util.concurrent.GlobalEventExecutor;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
-import org.opendaylight.netconf.api.NetconfMessage;
-import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
-import org.opendaylight.netconf.client.SimpleNetconfClientSessionListener;
-import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
-import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
-import org.opendaylight.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
-import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
-import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
-import org.opendaylight.netconf.impl.SessionIdProvider;
-import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
-import org.opendaylight.netconf.impl.osgi.NetconfMonitoringServiceImpl;
-import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
-import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
-import org.opendaylight.netconf.util.test.XmlFileLoader;
-import org.opendaylight.protocol.framework.NeverReconnectStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
-
-public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
-
- public static final String LOOPBACK_ADDRESS = "127.0.0.1";
- public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000;
- private static final int RESOURCE_TIMEOUT_MINUTES = 2;
-
- static ModuleFactory[] FACTORIES =
- {new TestImplModuleFactory(), new DepTestImplModuleFactory(), new NetconfTestImplModuleFactory(),
- new IdentityTestModuleFactory(), new MultipleDependenciesModuleFactory()};
-
- protected ConfigSubsystemFacadeFactory configSubsystemFacadeFactory;
- private EventLoopGroup nettyThreadgroup;
- private HashedWheelTimer hashedWheelTimer;
-
- private NetconfClientDispatcherImpl clientDispatcher;
- private Channel serverTcpChannel;
-
- private NetconfMessage getConfig;
- private NetconfMessage get;
-
- /**
- * @Before in subclasses is called after this method.
- */
- @Before
- public void setUpAbstractNetconfConfigTest() throws Exception {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORIES));
-
- nettyThreadgroup = new NioEventLoopGroup();
- hashedWheelTimer = new HashedWheelTimer();
-
- loadMessages();
-
- setUpTestInitial();
-
- final AggregatedNetconfOperationServiceFactory factoriesListener =
- new AggregatedNetconfOperationServiceFactory();
- final NetconfMonitoringService netconfMonitoringService = getNetconfMonitoringService(factoriesListener);
- configSubsystemFacadeFactory =
- new ConfigSubsystemFacadeFactory(configRegistryClient, configRegistryClient, getYangStore());
- factoriesListener.onAddNetconfOperationServiceFactory(
- new NetconfOperationServiceFactoryImpl(configSubsystemFacadeFactory));
- factoriesListener.onAddNetconfOperationServiceFactory(
- new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
- new NetconfMonitoringOperationService(netconfMonitoringService)));
-
- for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories(
- factoriesListener)) {
- factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
- }
-
- serverTcpChannel = startNetconfTcpServer(factoriesListener, netconfMonitoringService);
- clientDispatcher =
- new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
- }
-
- /**
- * Called before setUp method is executed, so test classes can set up resources before
- * setUpAbstractNetconfConfigTest method is called.
- */
- protected void setUpTestInitial() throws Exception {}
-
- private void loadMessages() throws Exception {
- this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
- this.get = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
- }
-
- public NetconfMessage getGetConfig() {
- return getConfig;
- }
-
- public NetconfMessage getGet() {
- return get;
- }
-
- private Channel startNetconfTcpServer(final AggregatedNetconfOperationServiceFactory listener,
- final NetconfMonitoringService monitoring) throws Exception {
- final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring);
-
- final ChannelFuture s;
- if (getTcpServerAddress() instanceof LocalAddress) {
- s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress()));
- } else {
- s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress()));
- }
- s.await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
- return s.channel();
- }
-
- protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories(
- final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
- return Collections.emptySet();
- }
-
- protected NetconfMonitoringService getNetconfMonitoringService(
- final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
- return new NetconfMonitoringServiceImpl(factoriesListener);
- }
-
- protected abstract SocketAddress getTcpServerAddress();
-
- public NetconfClientDispatcherImpl getClientDispatcher() {
- return clientDispatcher;
- }
-
- private HardcodedYangStoreService getYangStore() throws IOException {
- final Collection<InputStream> yangDependencies = getBasicYangs();
- return new HardcodedYangStoreService(yangDependencies, getBindingRuntimeContext());
- }
-
- static Collection<InputStream> getBasicYangs() throws IOException {
-
- final List<String> paths = Arrays.asList("/META-INF/yang/config@2013-04-05.yang",
- "/META-INF/yang/rpc-context@2013-06-17.yang",
- "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
- "/META-INF/yang/test-types.yang", "/META-INF/yang/test-groups.yang",
- "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
-
- final Collection<InputStream> yangDependencies = new ArrayList<>();
- final List<String> failedToFind = new ArrayList<>();
- for (final String path : paths) {
- final InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
- if (resourceAsStream == null) {
- failedToFind.add(path);
- } else {
- yangDependencies.add(resourceAsStream);
- }
- }
- assertEquals("Some yang files were not found", Collections.<String>emptyList(), failedToFind);
- return yangDependencies;
- }
-
- protected NetconfServerDispatcherImpl createDispatcher(
- final AggregatedNetconfOperationServiceFactory factoriesListener,
- final NetconfMonitoringService sessionMonitoringService) {
- final SessionIdProvider idProvider = new SessionIdProvider();
-
- final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory =
- new NetconfServerSessionNegotiatorFactory(hashedWheelTimer, factoriesListener, idProvider,
- SERVER_CONNECTION_TIMEOUT_MILLIS, sessionMonitoringService);
-
- final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
- new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
- return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
- }
-
- protected HashedWheelTimer getHashedWheelTimer() {
- return hashedWheelTimer;
- }
-
- protected EventLoopGroup getNettyThreadgroup() {
- return nettyThreadgroup;
- }
-
- /**
- * @After in subclasses is be called before this.
- */
- @After
- public void cleanUpNetconf() throws Exception {
- serverTcpChannel.close().await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
- hashedWheelTimer.stop();
- nettyThreadgroup.shutdownGracefully().await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
- }
-
- public NetconfClientConfiguration getClientConfiguration(final InetSocketAddress tcpAddress, final int timeout) {
- final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
- b.withAddress(tcpAddress);
- b.withSessionListener(new SimpleNetconfClientSessionListener());
- b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, timeout));
- b.withConnectionTimeoutMillis(timeout);
- return b.build();
- }
-
- public static final class HardcodedYangStoreService extends YangStoreService {
- public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams,
- final BindingRuntimeContext bindingRuntimeContext) throws IOException {
- super(new SchemaContextProvider() {
- @Override
- public SchemaContext getSchemaContext() {
- return getSchema(inputStreams);
- }
- }, new SchemaSourceProvider<YangTextSchemaSource>() {
- @Override
- public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
- SourceIdentifier sourceIdentifier) {
-
- return null;
- }
- });
-
- refresh(bindingRuntimeContext);
- }
-
- private static SchemaContext getSchema(final Collection<? extends InputStream> inputStreams) {
- final ArrayList<InputStream> byteArrayInputStreams = new ArrayList<>();
- for (final InputStream inputStream : inputStreams) {
- assertNotNull(inputStream);
- final byte[] content;
- try {
- content = ByteStreams.toByteArray(inputStream);
- } catch (IOException e) {
- throw new IllegalStateException("Cannot read " + inputStream, e);
- }
- final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
- byteArrayInputStreams.add(byteArrayInputStream);
- }
-
- for (final InputStream inputStream : byteArrayInputStreams) {
- try {
- inputStream.reset();
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- try {
- return YangInferencePipeline.RFC6020_REACTOR.newBuild().buildEffective(byteArrayInputStreams);
- } catch (SourceException | ReactorException e) {
- throw Throwables.propagate(e);
- }
- }
-
- @Override
- public EnumResolver getEnumResolver() {
- return new EnumResolver() {
- @Override
- public String fromYang(final String enumType, final String enumYangValue) {
- return BindingMapping.getClassName(enumYangValue);
- }
-
- @Override
- public String toYang(final String enumType, final String enumJavaValue) {
- return enumJavaValue.toLowerCase();
- }
- };
- }
- }
-}
+++ /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.it;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.opendaylight.controller.config.util.xml.XmlUtil.readXmlToDocument;
-import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElementWithName;
-import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertElementsCount;
-
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.Lists;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.List;
-import javax.management.InstanceNotFoundException;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
-import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.impl.ConfigPersisterNotificationHandler;
-import org.opendaylight.netconf.api.NetconfMessage;
-import org.opendaylight.netconf.client.TestingNetconfClient;
-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.sal.binding.generator.util.BindingRuntimeContext;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
-
- public static final int PORT = 12026;
- private static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
-
- @Override
- protected SocketAddress getTcpServerAddress() {
- return TCP_ADDRESS;
- }
-
- @Test
- public void testNetconfCommitNotifications() throws Exception {
- final VerifyingNotificationListener notificationVerifier = createCommitNotificationListener();
- final VerifyingPersister mockedAggregator = mockAggregator();
-
- try (TestingNetconfClient persisterClient = new TestingNetconfClient("persister", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) {
- try (ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler(
- platformMBeanServer, mockedAggregator, configSubsystemFacadeFactory)) {
-
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) {
- NetconfMessage response = netconfClient.sendMessage(loadEditConfigMessage());
- assertContainsElementWithName(response.getDocument(), "ok");
- response = netconfClient.sendMessage(loadCommitMessage());
- assertContainsElementWithName(response.getDocument(), "ok");
-
- response = netconfClient.sendMessage(loadGetConfigMessage());
- assertContainsElementWithName(response.getDocument(), "modules");
- assertContainsElementWithName(response.getDocument(), "services");
- }
- }
- }
-
- notificationVerifier.assertNotificationCount(1);
-
- mockedAggregator.assertSnapshotCount(1);
- // Capabilities are stripped for persister
- mockedAggregator.assertSnapshotContent(0, 4, 3, 3);
- }
-
- @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);
- final HashBiMap<String, String> toBeReturned = HashBiMap.create();
- toBeReturned.put("two", "Two");
- toBeReturned.put("one", "One");
- toBeReturned.put("version1", "Version1");
- doReturn(toBeReturned).when(ret).getEnumMapping(anyString());
- return ret;
- }
-
- private VerifyingPersister mockAggregator() throws IOException {
- return new VerifyingPersister();
- }
-
- private VerifyingNotificationListener createCommitNotificationListener() throws InstanceNotFoundException {
- final VerifyingNotificationListener listener = new VerifyingNotificationListener();
- platformMBeanServer.addNotificationListener(ConfigJMXNotification.OBJECT_NAME, listener, null, null);
- return listener;
- }
-
- private NetconfMessage loadGetConfigMessage() throws Exception {
- return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
- }
-
- private NetconfMessage loadEditConfigMessage() throws Exception {
- return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig.xml");
- }
-
- private NetconfMessage loadCommitMessage() throws Exception {
- return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml");
- }
-
- private static class VerifyingNotificationListener implements NotificationListener {
- public List<Notification> notifications = Lists.newArrayList();
-
- @Override
- public void handleNotification(final Notification notification, final Object handback) {
- this.notifications.add(notification);
- }
-
- void assertNotificationCount(final Object size) {
- assertEquals(size, notifications.size());
- }
-
- void assertNotificationContent(final int notificationIndex) {
- final Notification notification = notifications.get(notificationIndex);
- assertEquals(CommitJMXNotification.class, notification.getClass());
- }
- }
-
- private static class VerifyingPersister implements Persister {
-
- public List<ConfigSnapshotHolder> snapshots = Lists.newArrayList();
- private Persister mockedPersister;
-
- public VerifyingPersister() throws IOException {
- final Persister mockedAggregator = mock(Persister.class);
-
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final ConfigSnapshotHolder configSnapshot = (ConfigSnapshotHolder) invocation.getArguments()[0];
- snapshots.add(configSnapshot);
- return null;
- }
- }).when(mockedAggregator).persistConfig(any(ConfigSnapshotHolder.class));
-
- this.mockedPersister = mockedAggregator;
- }
-
- void assertSnapshotCount(final Object size) {
- assertEquals(size, snapshots.size());
- }
-
- void assertSnapshotContent(final int notificationIndex, final int expectedModulesSize, final int expectedServicesSize, final int expectedCapsSize)
- throws SAXException, IOException {
- final ConfigSnapshotHolder snapshot = snapshots.get(notificationIndex);
- final int capsSize = snapshot.getCapabilities().size();
- assertEquals("Expected capabilities count should be " + expectedCapsSize + " but was " + snapshot.getCapabilities(), expectedCapsSize, capsSize);
- final Document configSnapshot = readXmlToDocument(snapshot.getConfigSnapshot());
- assertElementsCount(configSnapshot, "module", expectedModulesSize);
- assertElementsCount(configSnapshot, "instance", expectedServicesSize);
- }
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder configSnapshotHolder) throws IOException {
- mockedPersister.persistConfig(configSnapshotHolder);
- }
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- return mockedPersister.loadLastConfigs();
- }
-
- @Override
- public void close() {
- mockedPersister.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.it;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import org.junit.Test;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.netconf.api.NetconfMessage;
-import org.opendaylight.netconf.api.monitoring.CapabilityListener;
-import org.opendaylight.netconf.client.TestingNetconfClient;
-import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
-import org.opendaylight.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.netconf.util.test.XmlFileLoader;
-import org.w3c.dom.Document;
-
-public class NetconfITMonitoringTest extends AbstractNetconfConfigTest {
-
- public static final int PORT = 12025;
- public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
- public static final TestingCapability TESTING_CAPABILITY = new TestingCapability();
-
- @Override
- protected InetSocketAddress getTcpServerAddress() {
- return TCP_ADDRESS;
- }
-
- @Test
- public void testGetResponseFromMonitoring() throws Exception {
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("client-monitoring", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 10000))) {
- try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("client-monitoring2", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 10000))) {
- Thread.sleep(500);
- final NetconfMessage response = netconfClient2.sendMessage(getGet());
- assertSessionElementsInResponse(response.getDocument(), 2);
- }
- Thread.sleep(500);
- final NetconfMessage response = netconfClient.sendMessage(getGet());
- assertSessionElementsInResponse(response.getDocument(), 1);
- }
- }
-
- @Test(timeout = 13 * 10000)
- public void testClientHelloWithAuth() throws Exception {
- String fileName = "netconfMessages/client_hello_with_auth.xml";
- final String hello = XmlFileLoader.fileToString(fileName);
-
- fileName = "netconfMessages/get.xml";
- final String get = XmlFileLoader.fileToString(fileName);
-
- final Socket sock = new Socket(TCP_ADDRESS.getHostName(), TCP_ADDRESS.getPort());
- sock.getOutputStream().write(hello.getBytes(StandardCharsets.UTF_8));
- final String separator = "]]>]]>";
-
- sock.getOutputStream().write(separator.getBytes(StandardCharsets.UTF_8));
- sock.getOutputStream().write(get.getBytes(StandardCharsets.UTF_8));
- sock.getOutputStream().write(separator.getBytes(StandardCharsets.UTF_8));
-
- final StringBuilder responseBuilder = new StringBuilder();
-
- try (InputStream inputStream = sock.getInputStream();
- InputStreamReader reader = new InputStreamReader(inputStream);
- BufferedReader buff = new BufferedReader(reader)) {
- String line;
- while ((line = buff.readLine()) != null) {
-
- responseBuilder.append(line);
- responseBuilder.append(System.lineSeparator());
-
- if(line.contains("</rpc-reply>"))
- break;
- }
- }
-
- sock.close();
-
- final String helloMsg = responseBuilder.substring(0, responseBuilder.indexOf(separator));
- Document doc = XmlUtil.readXmlToDocument(helloMsg);
- assertContainsElementWithText(doc, "urn:ietf:params:netconf:capability:candidate:1.0");
-
- final String replyMsg = responseBuilder.substring(responseBuilder.indexOf(separator) + separator.length());
- doc = XmlUtil.readXmlToDocument(replyMsg);
- assertContainsElementWithText(doc, "tomas");
- }
-
- private void assertSessionElementsInResponse(final Document document, final int i) {
- final int elementSize = document.getElementsByTagName("session-id").getLength();
- assertEquals("Incorrect number of session-id tags in " + XmlUtil.toString(document), i, elementSize);
- }
-
- public static AggregatedNetconfOperationServiceFactory getNetconfOperationProvider() throws Exception {
- final AggregatedNetconfOperationServiceFactory factoriesListener = mock(AggregatedNetconfOperationServiceFactory.class);
- final NetconfOperationService snap = mock(NetconfOperationService.class);
- try {
- doNothing().when(snap).close();
- } catch (final Exception e) {
- // not happening
- throw new IllegalStateException(e);
- }
- final Set<Capability> caps = Sets.newHashSet();
- caps.add(TESTING_CAPABILITY);
-
- doReturn(caps).when(factoriesListener).getCapabilities();
- doReturn(snap).when(factoriesListener).createService(anyString());
-
- AutoCloseable mock = mock(AutoCloseable.class);
- doNothing().when(mock).close();
- doReturn(mock).when(factoriesListener).registerCapabilityListener(any(CapabilityListener.class));
-
- return factoriesListener;
- }
-
- private static class TestingCapability implements Capability {
- @Override
- public String getCapabilityUri() {
- return "namespaceModuleRevision";
- }
-
- @Override
- public Optional<String> getModuleNamespace() {
- return Optional.of("namespace");
- }
-
- @Override
- public Optional<String> getModuleName() {
- return Optional.of("name");
- }
-
- @Override
- public Optional<String> getRevision() {
- return Optional.of("revision");
- }
-
- @Override
- public Optional<String> getCapabilitySchema() {
- return Optional.of("content");
- }
-
- @Override
- public List<String> getLocation() {
- return Collections.emptyList();
- }
- }
-}
+++ /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.it;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-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.mock;
-
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.local.LocalAddress;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.concurrent.GlobalEventExecutor;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.file.Files;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
-import org.junit.After;
-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.auth.AuthProvider;
-import org.opendaylight.netconf.client.NetconfClientDispatcher;
-import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
-import org.opendaylight.netconf.client.NetconfClientSessionListener;
-import org.opendaylight.netconf.client.SimpleNetconfClientSessionListener;
-import org.opendaylight.netconf.client.TestingNetconfClient;
-import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
-import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
-import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
-import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
-import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
-import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
-import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
-import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.ssh.SshProxyServer;
-import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
-import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
-import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
-import org.opendaylight.protocol.framework.NeverReconnectStrategy;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.xml.sax.SAXException;
-
-public class NetconfITSecureTest extends AbstractNetconfConfigTest {
-
- public static final int PORT = 12024;
- private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
-
- public static final String USERNAME = "user";
- public static final String PASSWORD = "pwd";
-
- private SshProxyServer sshProxyServer;
-
- private ExecutorService nioExec;
- private EventLoopGroup clientGroup;
- private ScheduledExecutorService minaTimerEx;
-
- @Before
- public void setUp() throws Exception {
- nioExec = Executors.newFixedThreadPool(1);
- clientGroup = new NioEventLoopGroup();
- minaTimerEx = Executors.newScheduledThreadPool(1);
- sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
- sshProxyServer.bind(
- new SshProxyServerConfigurationBuilder()
- .setBindingAddress(TLS_ADDRESS)
- .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
- .setAuthenticator(new AuthProvider() {
- @Override
- public boolean authenticated(String username, String password) {
- return true;
- }
- }
- )
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
- .setIdleTimeout(Integer.MAX_VALUE)
- .createSshProxyServerConfiguration());
- }
-
- @After
- public void tearDown() throws Exception {
- sshProxyServer.close();
- clientGroup.shutdownGracefully();
- minaTimerEx.shutdownNow();
- nioExec.shutdownNow();
- }
-
- @Test(timeout = 2*60*1000)
- public void testSecure() throws Exception {
- final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener(), TLS_ADDRESS))) {
- NetconfMessage response = netconfClient.sendMessage(getGetConfig());
- assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
- NetconfMessageUtil.isErrorMessage(response));
-
- final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
- " xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- " <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- " <identifier>config</identifier>\n" +
- " </get-schema>\n" +
- "</rpc>\n"));
-
- response = netconfClient.sendMessage(gs);
- assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
- NetconfMessageUtil.isErrorMessage(response));
- }
- }
-
- /**
- * Test all requests are handled properly and no mismatch occurs in listener
- */
- @Test(timeout = 6*60*1000)
- public void testSecureStress() throws Exception {
- final int requests = 4000;
-
- final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
- final NetconfDeviceCommunicator sessionListener = getSessionListener();
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener, TLS_ADDRESS))) {
-
- final AtomicInteger responseCounter = new AtomicInteger(0);
- final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
-
- for (int i = 0; i < requests; i++) {
- NetconfMessage getConfig = getGetConfig();
- getConfig = changeMessageId(getConfig, i);
- final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
- futures.add(netconfMessageFuture);
- Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
- @Override
- public void onSuccess(final RpcResult<NetconfMessage> result) {
- responseCounter.incrementAndGet();
- }
-
- @Override
- public void onFailure(final Throwable t) {
- throw new RuntimeException(t);
- }
- });
- }
-
- // Wait for every future
- for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
- try {
- future.get(3, TimeUnit.MINUTES);
- } catch (final TimeoutException e) {
- fail("Request " + futures.indexOf(future) + " is not responding");
- }
- }
-
- // Give future listeners some time to finish counter incrementation
- Thread.sleep(5000);
-
- assertEquals(requests, responseCounter.get());
- }
- }
-
- public static NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
- String s = XmlUtil.toString(getConfig.getDocument(), false);
- s = s.replace("101", Integer.toString(i));
- return new NetconfMessage(XmlUtil.readXmlToDocument(s));
- }
-
- static NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener,final InetSocketAddress tlsAddress) throws IOException {
- final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
- b.withAddress(tlsAddress);
- // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
- b.withSessionListener(sessionListener);
- b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
- b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
- b.withConnectionTimeoutMillis(5000);
- b.withAuthHandler(getAuthHandler());
- return b.build();
- }
-
- static NetconfDeviceCommunicator getSessionListener() {
- RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> mockedRemoteDevice = mock(RemoteDevice.class);
- doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionPreferences.class), any(NetconfDeviceCommunicator.class));
- doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
- return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test", InetSocketAddress.createUnresolved("localhost", 22)), mockedRemoteDevice);
- }
-
- public AuthProvider getAuthProvider() throws Exception {
- final AuthProvider mockAuth = mock(AuthProvider.class);
- doReturn("mockedAuth").when(mockAuth).toString();
- doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
- return mockAuth;
- }
-
- public static AuthenticationHandler getAuthHandler() throws IOException {
- return new LoginPassword(USERNAME, PASSWORD);
- }
-
- @Override
- protected LocalAddress getTcpServerAddress() {
- return NetconfConfigUtil.getNetconfLocalAddress();
- }
-}
+++ /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.it;
-
-import static java.lang.Thread.sleep;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.opendaylight.netconf.it.NetconfITSecureTest.getSessionListener;
-
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.util.HashedWheelTimer;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.netconf.api.NetconfMessage;
-import org.opendaylight.netconf.client.NetconfClientDispatcher;
-import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
-import org.opendaylight.netconf.client.TestingNetconfClient;
-import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
-import org.opendaylight.netconf.test.tool.Main.Params;
-import org.opendaylight.netconf.test.tool.NetconfDeviceSimulator;
-import org.opendaylight.netconf.util.test.XmlFileLoader;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-public class NetconfITSecureTestTool
-{
-
- //set up port both for testool device and test
- public static final int PORT = 17833;
- private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
-
- private String xmlFile = "netconfMessages/editConfig.xml";
-
- private ExecutorService msgExec = Executors.newFixedThreadPool(8);
-
- Collection<Future<?>> tasks = new LinkedList<Future<?>>();
-
- final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator();
-
- @Before
- public void setUp() throws Exception {
-
- //Set up parameters for testtool device
- Params params = new Params();
- params.debug = true;
- params.deviceCount = 1;
- params.startingPort = PORT;
- params.ssh = true;
- params.exi = true;
-
- final List<Integer> openDevices = netconfDeviceSimulator.start(params);
- }
-
- @After
- public void tearDown() throws Exception {
-
- }
-
- /**
- * Test all requests are handled properly and no mismatch occurs in listener
- */
- @Test(timeout = 6*60*1000)
- public void testSecureStress() throws Exception {
-
- final int requests = 4000;
-
- List<Future<?>> tasks = new ArrayList<>();
-
- final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), new HashedWheelTimer());
-
- final NetconfDeviceCommunicator sessionListener = getSessionListener();
-
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, NetconfITSecureTest.getClientConfiguration(sessionListener, TLS_ADDRESS));)
- {
-
- final AtomicInteger responseCounter = new AtomicInteger(0);
- final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
-
- for (int i = 0; i < requests; i++) {
-
- NetconfMessage getConfig = XmlFileLoader.xmlFileToNetconfMessage(xmlFile);
-
- getConfig = NetconfITSecureTest.changeMessageId(getConfig,i);
-
- Runnable worker = new NetconfITSecureTestToolRunnable(getConfig,i, sessionListener, futures, responseCounter);
-
- tasks.add(msgExec.submit(worker));
-
- }
-
- msgExec.shutdown();
-
- // Wait for every future
- for (final Future<?> task : tasks){
- try
- {
-
- task.get(3, TimeUnit.MINUTES);
- } catch (final TimeoutException e) {
- fail(String.format("Request %d is not responding", tasks.indexOf(task)));
- }
- }
-
- for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
- try {
-
- future.get(3, TimeUnit.MINUTES);
- } catch (final TimeoutException e) {
- fail(String.format("Reply %d is not responding", futures.indexOf(future)));
- }
- }
-
- sleep(5000);
-
- assertEquals(requests, responseCounter.get());
-
- }
- }
-
- class NetconfITSecureTestToolRunnable implements Runnable {
-
- private NetconfMessage getConfig;
- private int it;
- private NetconfDeviceCommunicator sessionListener;
- private List<ListenableFuture<RpcResult<NetconfMessage>>> futures;
- private AtomicInteger responseCounter;
-
- public NetconfITSecureTestToolRunnable(NetconfMessage getConfig, int it, NetconfDeviceCommunicator sessionListener, List<ListenableFuture<RpcResult<NetconfMessage>>> futures, AtomicInteger responseCounter){
- this.getConfig = getConfig;
- this.it = it;
- this.sessionListener = sessionListener;
- this.futures = futures;
- this.responseCounter = responseCounter;
- }
-
- @Override
- public void run(){
-
- ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture;
-
- netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
-
- futures.add(netconfMessageFuture);
- Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
-
- @Override
- public void onSuccess(final RpcResult<NetconfMessage> result) {
-
- if(result.isSuccessful()&result.getErrors().isEmpty()) {
- responseCounter.incrementAndGet();
- } else {
-
- fail(String.format("Message result not ok %s", result.getErrors().toString()));
-
- }
- }
-
- @Override
- public void onFailure(final Throwable t) {
-
- fail(String.format("Message failed %s", Throwables.getStackTraceAsString(t)));
-
- }
- }
- );
- }
- }
-
-}
+++ /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.it;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeoutException;
-import javax.management.ObjectName;
-import javax.xml.parsers.ParserConfigurationException;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-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.controller.config.yang.test.impl.DepTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
-import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
-import org.opendaylight.netconf.api.NetconfMessage;
-import org.opendaylight.netconf.client.NetconfClientDispatcher;
-import org.opendaylight.netconf.client.TestingNetconfClient;
-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.sal.binding.generator.util.BindingRuntimeContext;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
-
-public class NetconfITTest extends AbstractNetconfConfigTest {
-
- public static final int PORT = 12023;
- public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
-
- private NetconfMessage getConfigCandidate, editConfig, closeSession;
- private NetconfClientDispatcher clientDispatcher;
-
- @Before
- public void setUp() throws Exception {
- loadMessages();
- clientDispatcher = getClientDispatcher();
- }
-
- @Override
- protected InetSocketAddress getTcpServerAddress() {
- return TCP_ADDRESS;
- }
-
- private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
- this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
- this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
- this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
- }
-
- @Test
- public void testNetconfClientDemonstration() throws Exception {
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 4000))) {
-
- final Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
- final long sessionId = netconfClient.getSessionId();
-
- // NetconfMessage can be created :
- // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
-
- final NetconfMessage response = netconfClient.sendMessage(getGetConfig());
- response.getDocument();
- }
- }
-
- @Test
- public void testTwoSessions() throws Exception {
- try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000))) {
- try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000))) {
- assertNotNull(netconfClient2.getCapabilities());
- }
- }
- }
-
- @Test
- public void rpcReplyContainsAllAttributesTest() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><get/>" + "</rpc>";
- final Document doc = XmlUtil.readXmlToDocument(rpc);
- final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
- assertNotNull(message);
- final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
- final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
-
- assertSameAttributes(expectedAttributes, returnedAttributes);
- }
- }
-
- private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
- assertNotNull("Expecting 4 attributes", returnedAttributes);
- assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
-
- for (int i = 0; i < expectedAttributes.getLength(); i++) {
- final Node expAttr = expectedAttributes.item(i);
- final Node attr = returnedAttributes.item(i);
- assertEquals(expAttr.getNodeName(), attr.getNodeName());
- assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
- assertEquals(expAttr.getTextContent(), attr.getTextContent());
- }
- }
-
- @Test
- public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><commit/>" + "</rpc>";
- final Document doc = XmlUtil.readXmlToDocument(rpc);
- final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
- final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
- final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
-
- assertSameAttributes(expectedAttributes, returnedAttributes);
- }
- }
-
- @Test
- public void rpcOutputContainsCorrectNamespace() throws Exception {
- final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
- final ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
- final ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
- final NetconfTestImplModuleMXBean proxy = configRegistryClient
- .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
- proxy.setTestingDep(dep);
- proxy.setSimpleShort((short) 0);
-
- transaction.commit();
-
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
-
- final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<no-arg xmlns=\""
- + expectedNamespace
- + "\"> "
- + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
- + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
- final Document doc = XmlUtil.readXmlToDocument(rpc);
- final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
-
- final Element rpcReply = message.getDocument().getDocumentElement();
- final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
- assertEquals("result", resultElement.getName());
-
- final String namespace = resultElement.getNamespaceAttribute();
- assertEquals(expectedNamespace, namespace);
- }
- }
-
- @Test
- public void testCloseSession() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
-
- // edit config
- Document rpcReply = netconfClient.sendMessage(this.editConfig)
- .getDocument();
- assertIsOK(rpcReply);
-
- rpcReply = netconfClient.sendMessage(this.closeSession)
- .getDocument();
-
- assertIsOK(rpcReply);
- }
- }
-
- @Test
- public void testEditConfig() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- // send edit_config.xml
- final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
- assertIsOK(rpcReply);
- }
- }
-
- @Test
- public void testValidate() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- // begin transaction
- Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
- assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
-
- // operations empty
- rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
- .getDocument();
- assertIsOK(rpcReply);
- }
- }
-
- private void assertIsOK(final Document rpcReply) throws DocumentedException {
- assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
- assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
- }
-
- private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, DocumentedException {
- return assertGetConfigWorks(netconfClient, getGetConfig());
- }
-
- private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
- throws InterruptedException, ExecutionException, TimeoutException, DocumentedException {
- final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
- assertNotNull(rpcReply);
- assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
- return rpcReply.getDocument();
- }
-
- @Test
- public void testGetConfig() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- assertGetConfigWorks(netconfClient);
- }
- }
-
- @Test
- public void createYangTestBasedOnYuma() throws Exception {
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- Document rpcReply = netconfClient.sendMessage(
- XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
- .getDocument();
- assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
- assertIsOK(rpcReply);
- assertGetConfigWorks(netconfClient, this.getConfigCandidate);
- rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
- .getDocument();
- assertIsOK(rpcReply);
-
- final ObjectName on = new ObjectName(
- "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
- final Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
- assertEquals(cfgBeans, Sets.newHashSet(on));
- }
- }
-
- private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
- final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), clientDispatcher, getClientConfiguration(address, 5000));
- assertEquals(expected, Long.toString(netconfClient.getSessionId()));
- return netconfClient;
- }
-
- @Test
- public void testIdRef() throws Exception {
- final NetconfMessage editId = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_identities.xml");
- final NetconfMessage commit = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml");
-
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- assertIsOK(netconfClient.sendMessage(editId).getDocument());
- assertIsOK(netconfClient.sendMessage(commit).getDocument());
-
- final NetconfMessage response = netconfClient.sendMessage(getGetConfig());
-
- assertThat(XmlUtil.toString(response.getDocument()), containsString("<afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</afi>"));
- assertThat(XmlUtil.toString(response.getDocument()), containsString("<afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</afi>"));
- assertThat(XmlUtil.toString(response.getDocument()), containsString("<safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</safi>"));
- assertThat(XmlUtil.toString(response.getDocument()), containsString("<safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</safi>"));
-
- } catch (final Exception e) {
- fail(Throwables.getStackTraceAsString(e));
- }
- }
-
- @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);
- return ret;
- }
-
- @Test
- public void testMultipleDependencies() throws Exception {
- // push first xml, should add parent and d1,d2 dependencies
- try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
- final Document rpcReply = netconfClient.sendMessage(
- XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps1.xml"))
- .getDocument();
- assertIsOK(rpcReply);
- commit(netconfClient);
- }
- // verify that parent.getTestingDeps == d1,d2
- final MultipleDependenciesModuleMXBean parentProxy = configRegistryClient.newMXBeanProxy(
- configRegistryClient.lookupConfigBean(MultipleDependenciesModuleFactory.NAME, "parent"),
- MultipleDependenciesModuleMXBean.class);
- {
- final List<ObjectName> testingDeps = parentProxy.getTestingDeps();
- assertEquals(2, testingDeps.size());
- final Set<String> actualRefs = getServiceReferences(testingDeps);
- assertEquals(Sets.newHashSet("ref_d1", "ref_d2"), actualRefs);
- }
-
- // push second xml, should add d3 to parent's dependencies
- mergeD3(parentProxy);
- // push second xml again, to test that d3 is not added again
- mergeD3(parentProxy);
- }
-
- public void mergeD3(final MultipleDependenciesModuleMXBean parentProxy) throws Exception {
- try (TestingNetconfClient netconfClient = new TestingNetconfClient(
- "test " + TCP_ADDRESS.toString(), clientDispatcher, getClientConfiguration(TCP_ADDRESS, 5000))) {
-
- final Document rpcReply = netconfClient.sendMessage(
- XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps2.xml"))
- .getDocument();
- assertIsOK(rpcReply);
- commit(netconfClient);
- }
- {
- final List<ObjectName> testingDeps = parentProxy.getTestingDeps();
- assertEquals(3, testingDeps.size());
- final Set<String> actualRefs = getServiceReferences(testingDeps);
- assertEquals(Sets.newHashSet("ref_d1", "ref_d2", "ref_d3"), actualRefs);
- }
- }
-
- public Set<String> getServiceReferences(final List<ObjectName> testingDeps) {
- return new HashSet<>(Lists.transform(testingDeps, ObjectNameUtil::getReferenceName));
- }
-
- public void commit(final TestingNetconfClient netconfClient) throws Exception {
- final Document rpcReply;
- rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
- .getDocument();
- assertIsOK(rpcReply);
- }
-}
+++ /dev/null
-<configuration scan="true">
-
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
- </encoder>
- </appender>
-
- <logger name="org.opendaylight.controller.netconf" level="INFO"/>
- <logger name="org.opendaylight.controller.sal.connect.netconf" level="DEBUG"/>
-
- <root level="error">
- <appender-ref ref="STDOUT" />
- </root>
-
-</configuration>
+++ /dev/null
-<rpc message-id="a" a="64" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-<edit-config>
- <target>
- <candidate/>
- </target>
- <test-option>
- set
- </test-option>
- <default-operation>merge</default-operation>
- <config>
- <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <module>
- <type xmlns:test-impl="urn:opendaylight:params:xml:ns:yang:controller:test:impl">
- test-impl:impl-identity-test
- </type>
- <name>id-test</name>
- <identities>
- <afi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity1</afi>
- <safi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity2</safi>
- </identities>
- <identities>
- <afi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity2</afi>
- <safi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity1</safi>
- </identities>
- <identities-container>
- <afi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity2</afi>
- </identities-container>
- <afi xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:test:types">prefix:test-identity1</afi>
- </module>
- </modules>
-
- <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-
- </services>
- </config>
-</edit-config>
-</rpc>
}
@Override
- public Document execute(Document requestMessage) throws DocumentedException {
+ public Document execute(Document requestMessage) {
throw new IllegalStateException("This execution represents the termination point in operation execution "
+ "and cannot be executed itself");
}
@Override
protected Element handle(final Document document, final XmlElement message,
- final NetconfOperationChainedExecution subsequentOperation)
- throws DocumentedException {
+ final NetconfOperationChainedExecution subsequentOperation) {
throw new UnsupportedOperationException("Never gets called");
}
}
@Override
public Set<NetconfOperation> getNetconfOperations() {
- return Sets.<NetconfOperation>newHashSet(new Get(monitor), new GetSchema(monitor));
+ return Sets.newHashSet(new Get(monitor), new GetSchema(monitor));
}
@Override
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.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
import org.w3c.dom.Document;
public class GetTest {
correctSubsequentResult = XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:"
+ "1.0\"><data></data></rpc-reply>");
- doReturn(new SessionsBuilder().setSession(Collections.<Session>emptyList()).build()).when(monitor)
+ doReturn(new SessionsBuilder().setSession(Collections.emptyList()).build()).when(monitor)
.getSessions();
- doReturn(new SchemasBuilder().setSchema(Collections.<Schema>emptyList()).build()).when(monitor).getSchemas();
+ doReturn(new SchemasBuilder().setSchema(Collections.emptyList()).build()).when(monitor).getSchemas();
doReturn(false).when(subsequentOperation).isExecutionTermination();
get = new Get(monitor);
<dependency>
<groupId>com.siemens.ct.exi</groupId>
<artifactId>exificient</artifactId>
- <version>0.9.7</version>
+ <version>1.0.1</version>
</dependency>
</dependencies>
</dependencyManagement>
*/
package org.opendaylight.netconf.nettyutil;
-import com.siemens.ct.exi.exceptions.EXIException;
-import com.siemens.ct.exi.exceptions.UnsupportedOption;
+import com.siemens.ct.exi.core.exceptions.EXIException;
+import com.siemens.ct.exi.core.exceptions.UnsupportedOption;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
-import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.TimeUnit;
} else {
final Optional<SslHandler> sslHandler = getSslHandler(channel);
if (sslHandler.isPresent()) {
- Future<Channel> future = sslHandler.get().handshakeFuture();
- future.addListener(new GenericFutureListener<Future<? super Channel>>() {
- @Override
- public void operationComplete(final Future<? super Channel> future) {
- Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
- LOG.debug("Ssl handshake complete");
- start();
- }
+ sslHandler.get().handshakeFuture().addListener(future -> {
+ Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
+ LOG.debug("Ssl handshake complete");
+ start();
});
} else {
start();
private static Optional<SslHandler> getSslHandler(final Channel channel) {
final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
- return sslHandler == null ? Optional.<SslHandler>absent() : Optional.of(sslHandler);
+ return sslHandler == null ? Optional.absent() : Optional.of(sslHandler);
}
public P getSessionPreferences() {
LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
changeState(State.FAILED);
- channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
- @Override
- public void operationComplete(final ChannelFuture future) throws Exception {
- if (future.isSuccess()) {
- LOG.debug("Channel {} closed: success", future.channel());
- } else {
- LOG.warn("Channel {} closed: fail", future.channel());
- }
+ channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
+ if (future.isSuccess()) {
+ LOG.debug("Channel {} closed: success", future.channel());
+ } else {
+ LOG.warn("Channel {} closed: fail", future.channel());
}
});
}
package org.opendaylight.netconf.nettyutil.handler;
-import com.google.common.base.Preconditions;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
-import com.siemens.ct.exi.EXIFactory;
-import com.siemens.ct.exi.api.sax.SAXEncoder;
-import com.siemens.ct.exi.api.sax.SAXFactory;
-import com.siemens.ct.exi.exceptions.EXIException;
+import com.siemens.ct.exi.core.EXIFactory;
+import com.siemens.ct.exi.core.exceptions.EXIException;
+import com.siemens.ct.exi.main.api.sax.SAXEncoder;
+import com.siemens.ct.exi.main.api.sax.SAXFactory;
import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
* OpenEXI does not allow us to directly prevent resolution of external entities. In order
* to prevent XXE attacks, we reuse a single no-op entity resolver.
*/
- private static final EntityResolver ENTITY_RESOLVER = new EntityResolver() {
- @Override
- public InputSource resolveEntity(final String publicId, final String systemId) {
- return new InputSource();
- }
- };
+ private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
/**
* Since we have a limited number of options we can have, instantiating a weak cache
private final SAXFactory exiFactory;
private NetconfEXICodec(final EXIFactory exiFactory) {
- this.exiFactory = new SAXFactory(Preconditions.checkNotNull(exiFactory));
+ this.exiFactory = new SAXFactory(requireNonNull(exiFactory));
}
public static NetconfEXICodec forParameters(final EXIParameters parameters) {
*/
package org.opendaylight.netconf.nettyutil.handler;
-import com.google.common.base.Preconditions;
-import com.siemens.ct.exi.exceptions.EXIException;
+import static java.util.Objects.requireNonNull;
+
+import com.siemens.ct.exi.core.exceptions.EXIException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufUtil;
private final DocumentBuilder documentBuilder;
private NetconfEXIToMessageDecoder(final XMLReader reader) {
- this.reader = Preconditions.checkNotNull(reader);
+ this.reader = requireNonNull(reader);
this.documentBuilder = UntrustedXML.newDocumentBuilder();
}
*/
package org.opendaylight.netconf.nettyutil.handler;
-import com.google.common.base.Preconditions;
-import com.siemens.ct.exi.api.sax.SAXEncoder;
-import com.siemens.ct.exi.exceptions.EXIException;
+import static java.util.Objects.requireNonNull;
+
+import com.siemens.ct.exi.core.exceptions.EXIException;
+import com.siemens.ct.exi.main.api.sax.SAXEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
private final NetconfEXICodec codec;
private NetconfMessageToEXIEncoder(final NetconfEXICodec codec) {
- this.codec = Preconditions.checkNotNull(codec);
+ this.codec = requireNonNull(codec);
}
public static NetconfMessageToEXIEncoder create(final NetconfEXICodec codec) {
private final Optional<String> clientId;
public NetconfMessageToXMLEncoder() {
- this(Optional.<String>absent());
+ this(Optional.absent());
}
public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
-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;
@Override
@VisibleForTesting
public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
- throws IOException, SAXException, NetconfDocumentedException {
+ throws IOException, SAXException {
if (in.readableBytes() == 0) {
LOG.debug("No more content in incoming buffer.");
return;
}
}
- private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc)
- throws NetconfDocumentedException {
+ private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc) {
NetconfMessage msg = new NetconfMessage(doc);
if (NetconfHelloMessage.isHelloMessage(msg)) {
if (additionalHeader != null) {
*/
package org.opendaylight.netconf.nettyutil.handler.exi;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-import com.siemens.ct.exi.CodingMode;
-import com.siemens.ct.exi.EXIFactory;
-import com.siemens.ct.exi.EncodingOptions;
-import com.siemens.ct.exi.FidelityOptions;
-import com.siemens.ct.exi.exceptions.UnsupportedOption;
-import com.siemens.ct.exi.helpers.DefaultEXIFactory;
+import com.siemens.ct.exi.core.CodingMode;
+import com.siemens.ct.exi.core.EXIFactory;
+import com.siemens.ct.exi.core.EncodingOptions;
+import com.siemens.ct.exi.core.FidelityOptions;
+import com.siemens.ct.exi.core.exceptions.UnsupportedOption;
+import com.siemens.ct.exi.core.helpers.DefaultEXIFactory;
import java.util.Objects;
import org.opendaylight.netconf.api.xml.XmlElement;
import org.slf4j.Logger;
private final CodingMode codingMode;
public EXIParameters(final CodingMode codingMode, final FidelityOptions fidelityOptions) {
- this.fidelityOptions = Preconditions.checkNotNull(fidelityOptions);
- this.codingMode = Preconditions.checkNotNull(codingMode);
+ this.fidelityOptions = requireNonNull(fidelityOptions);
+ this.codingMode = requireNonNull(codingMode);
}
@VisibleForTesting
private GenericFutureListener negotiationFutureListener;
public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
- final Future<?> negotiationFuture) throws IOException {
+ final Future<?> negotiationFuture) {
this(authenticationHandler, sshClient);
this.negotiationFuture = negotiationFuture;
}
*
* @param authenticationHandler authentication handler
* @param sshClient started SshClient
- * @throws IOException if the I/O operation fails
*/
public AsyncSshHandler(final AuthenticationHandler authenticationHandler,
- final SshClient sshClient) throws IOException {
+ final SshClient sshClient) {
this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
this.sshClient = Preconditions.checkNotNull(sshClient);
}
- public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler)
- throws IOException {
+ public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
}
* @param authenticationHandler authentication handler
* @param negotiationFuture negotiation future
* @return {@code AsyncSshHandler}
- * @throws IOException if the I/O operation fails
*/
public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
- final Future<?> negotiationFuture) throws IOException {
+ final Future<?> negotiationFuture) {
return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
}
ClientChannel localChannel = channel;
sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
- msg -> ctx.fireChannelRead(msg), localChannel.toString(), localChannel.getAsyncOut());
+ ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
// if readAsyncListener receives immediate close,
// it will close this handler and closing this handler sets channel variable to null
}
@Override
- public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
+ public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
disconnect(ctx, promise);
}
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import com.google.common.collect.Lists;
-import com.siemens.ct.exi.api.sax.SAXEncoder;
-import com.siemens.ct.exi.exceptions.EXIException;
+import com.siemens.ct.exi.core.exceptions.EXIException;
+import com.siemens.ct.exi.main.api.sax.SAXEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.transform.TransformerException;
assertEquals((byte)0, buffer.array()[i]);
}
- final List<Object> out = Lists.newArrayList();
+ final List<Object> out = new ArrayList<>();
netconfEXIToMessageDecoder.decode(null, buffer, out);
XMLUnit.compareXML(msg.getDocument(), ((NetconfMessage) out.get(0)).getDocument());
import static org.junit.Assert.assertEquals;
-import com.siemens.ct.exi.CodingMode;
-import com.siemens.ct.exi.EXIFactory;
-import com.siemens.ct.exi.FidelityOptions;
+import com.siemens.ct.exi.core.CodingMode;
+import com.siemens.ct.exi.core.EXIFactory;
+import com.siemens.ct.exi.core.FidelityOptions;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
-import com.siemens.ct.exi.CodingMode;
-import com.siemens.ct.exi.FidelityOptions;
+import com.siemens.ct.exi.core.CodingMode;
+import com.siemens.ct.exi.core.FidelityOptions;
import java.util.Arrays;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
public void onSuccess(final SshFutureListener<IoReadFuture> result) {
doReturn(new IllegalStateException()).when(mockedReadFuture).getException();
doReturn(mockedReadFuture).when(mockedReadFuture)
- .removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+ .removeListener(Matchers.any());
doReturn(true).when(asyncOut).isClosing();
doReturn(true).when(asyncOut).isClosed();
result.operationComplete(mockedReadFuture);
public void onSuccess(final SshFutureListener<IoReadFuture> result) {
doReturn(new IllegalStateException()).when(mockedReadFuture).getException();
doReturn(mockedReadFuture).when(mockedReadFuture)
- .removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+ .removeListener(Matchers.any());
result.operationComplete(mockedReadFuture);
}
}, MoreExecutors.directExecutor());
private static IoOutputStream getMockedIoOutputStream() {
final IoOutputStream mock = mock(IoOutputStream.class);
final IoWriteFuture ioWriteFuture = mock(IoWriteFuture.class);
- doReturn(ioWriteFuture).when(ioWriteFuture).addListener(Matchers.<SshFutureListener<IoWriteFuture>>any());
+ doReturn(ioWriteFuture).when(ioWriteFuture).addListener(Matchers.any());
doReturn(true).when(ioWriteFuture).isWritten();
Futures.addCallback(stubAddListener(ioWriteFuture), new SuccessFutureListener<IoWriteFuture>() {
final IoInputStream mock = mock(IoInputStream.class);
final IoReadFuture ioReadFuture = mock(IoReadFuture.class);
doReturn(null).when(ioReadFuture).getException();
- doReturn(ioReadFuture).when(ioReadFuture).removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+ doReturn(ioReadFuture).when(ioReadFuture).removeListener(Matchers.any());
doReturn(5).when(ioReadFuture).getRead();
doReturn(new ByteArrayBuffer(new byte[]{0, 1, 2, 3, 4})).when(ioReadFuture).getBuffer();
- doReturn(ioReadFuture).when(ioReadFuture).addListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+ doReturn(ioReadFuture).when(ioReadFuture).addListener(Matchers.any());
// Always success for read
Futures.addCallback(stubAddListener(ioReadFuture), new SuccessFutureListener<IoReadFuture>() {
.registerNotificationListener(streamNameType, new NotificationSubscription(netconfSession, filter));
subscriptions.add(notificationListenerRegistration);
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
private static StreamNameType parseStreamIfPresent(final XmlElement operationElement) throws DocumentedException {
@Override
protected Element handle(final Document document, final XmlElement message,
- final NetconfOperationChainedExecution subsequentOperation)
- throws DocumentedException {
+ final NetconfOperationChainedExecution subsequentOperation) {
throw new UnsupportedOperationException("Never gets called");
}
}
@Override
- public void close() throws Exception {
+ public void close() {
}
}
* Transform base notification for capabilities into NetconfNotification.
*/
public static NetconfNotification transform(final Notification notification, SchemaPath path) {
- return transform(notification, Optional.<Date>absent(), path);
+ return transform(notification, Optional.absent(), path);
}
public static NetconfNotification transform(final Notification notification,
private NetconfNotificationManager netconfNotificationManager;
@Override
- public void start(final BundleContext context) throws Exception {
+ public void start(final BundleContext context) {
netconfNotificationManager = new NetconfNotificationManager();
// Add properties to autowire with netconf-impl instance for cfg subsystem
final Dictionary<String, String> props = new Hashtable<>();
final NetconfOperationServiceFactory netconfOperationServiceFactory = new NetconfOperationServiceFactory() {
private final Set<Capability> capabilities =
- Collections.<Capability>singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
+ Collections.singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
@Override
public Set<Capability> getCapabilities() {
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- listener.onCapabilitiesChanged(capabilities, Collections.<Capability>emptySet());
- return () -> listener.onCapabilitiesChanged(Collections.<Capability>emptySet(), capabilities);
+ listener.onCapabilitiesChanged(capabilities, Collections.emptySet());
+ return () -> listener.onCapabilitiesChanged(Collections.emptySet(), capabilities);
}
@Override
@Override
public Set<NetconfOperation> getNetconfOperations() {
- return Sets.<NetconfOperation>newHashSet(
+ return Sets.newHashSet(
new Get(netconfSessionIdForReporting, netconfNotificationManager),
createSubscription);
}
}
@Override
- public void stop(final BundleContext context) throws Exception {
+ public void stop(final BundleContext context) {
if (netconfNotificationCollectorServiceRegistration != null) {
netconfNotificationCollectorServiceRegistration.unregister();
netconfNotificationCollectorServiceRegistration = null;
import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider;
import org.opendaylight.netconf.auth.AuthProvider;
import org.opendaylight.netconf.util.NetconfConfiguration;
-import org.osgi.framework.InvalidSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Called via blueprint
@SuppressWarnings("unused")
- public void init() throws IOException, InvalidSyntaxException {
+ public void init() throws IOException {
minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE,
runnable -> new Thread(runnable, "netconf-ssh-server-mina-timers"));
clientGroup = new NioEventLoopGroup();
}
private SshProxyServer startSSHServer()
- throws IOException, InvalidSyntaxException {
+ throws IOException {
final InetSocketAddress sshSocketAddress = netconfConfiguration.getSshServerAddress();
LOG.info("Starting netconf SSH server at {}", sshSocketAddress);
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
-import io.netty.util.concurrent.GenericFutureListener;
-import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
}
@Override
- public void start(final Environment env) throws IOException {
+ public void start(final Environment env) {
LOG.trace("Establishing internal connection to netconf server for client: {}", getClientAddress());
final Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
@Override
- public void initChannel(final LocalChannel ch) throws Exception {
+ public void initChannel(final LocalChannel ch) {
ch.pipeline()
.addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
}
});
clientChannelFuture = clientBootstrap.connect(localAddress);
- clientChannelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
-
- @Override
- public void operationComplete(final ChannelFuture future) throws Exception {
- if (future.isSuccess()) {
- clientChannel = clientChannelFuture.channel();
- } else {
- LOG.warn("Unable to establish internal connection to netconf server for client: {}",
- getClientAddress());
- Preconditions.checkNotNull(callback, "Exit callback must be set");
- callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
- + getClientAddress());
- }
+ clientChannelFuture.addListener(future -> {
+ if (future.isSuccess()) {
+ clientChannel = clientChannelFuture.channel();
+ } else {
+ LOG.warn("Unable to establish internal connection to netconf server for client: {}",
+ getClientAddress());
+ Preconditions.checkNotNull(callback, "Exit callback must be set");
+ callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
+ + getClientAddress());
}
});
}
clientChannelFuture.cancel(true);
if (clientChannel != null) {
- clientChannel.close().addListener(new GenericFutureListener<ChannelFuture>() {
-
- @Override
- public void operationComplete(final ChannelFuture future) throws Exception {
- if (!future.isSuccess()) {
- LOG.warn("Unable to release internal connection to netconf server on channel: {}",
- clientChannel);
- }
+ clientChannel.close().addListener(future -> {
+ if (!future.isSuccess()) {
+ LOG.warn("Unable to release internal connection to netconf server on channel: {}",
+ clientChannel);
}
});
}
}
@Override
- public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
+ public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
asyncSshHandlerWriter.write(ctx, msg, ctx.newPromise());
}
}
@Override
- public void close() throws Exception {
+ public void close() {
if (tcpServer.isDone()) {
tcpServer.channel().close();
} else {
import java.net.InetSocketAddress;
import org.opendaylight.netconf.tcp.netty.ProxyServer;
import org.opendaylight.netconf.util.NetconfConfiguration;
-import org.osgi.framework.InvalidSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Called via blueprint
@SuppressWarnings("unused")
- public void init() throws InvalidSyntaxException {
+ public void init() {
final InetSocketAddress address = netconfConfiguration.getTcpServerAddress();
if (address.getAddress().isAnyLocalAddress()) {
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
- public void initChannel(SocketChannel ch) throws Exception {
+ public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new ProxyServerHandler(clientBootstrap, localAddress));
}
});
final ProxyClientHandler clientHandler = new ProxyClientHandler(remoteCtx);
clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
@Override
- public void initChannel(LocalChannel ch) throws Exception {
+ public void initChannel(LocalChannel ch) {
ch.pipeline().addLast(clientHandler);
}
});
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
}
@Override
- public void close() throws Exception {
+ public void close() {
if (!closed.compareAndSet(false, true)) {
return;
}
future.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(final Throwable failure, final Object success) throws Throwable {
+ public void onComplete(final Throwable failure, final Object success) {
if (failure != null) {
LOG.error("Failed to refresh master actor data: {}", failure);
return;
dataChangeListenerRegistration = null;
}
- contexts.values().forEach(netconfTopologyContext -> close(netconfTopologyContext));
-
- clusterRegistrations.values().forEach(
- clusterSingletonServiceRegistration -> close(clusterSingletonServiceRegistration));
+ contexts.values().forEach(NetconfTopologyManager::close);
+ clusterRegistrations.values().forEach(NetconfTopologyManager::close);
contexts.clear();
clusterRegistrations.clear();
scalaFuture.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(final Throwable failure, final Object success) throws Throwable {
+ public void onComplete(final Throwable failure, final Object success) {
if (failure != null) {
promise.failure(failure);
return;
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public void handleReceive(final Object message) throws Exception {
+ public void handleReceive(final Object message) {
LOG.debug("{}: received message {}", id, message);
if (message instanceof CreateInitialMasterActorData) { // master
}
@SuppressWarnings("checkstyle:IllegalThrows")
- public void handle(final Object message, final ActorRef sender, final ActorRef self) throws Throwable {
+ public void handle(final Object message, final ActorRef sender, final ActorRef self) {
if (message instanceof ReadRequest) {
final ReadRequest readRequest = (ReadRequest) message;
}
@Override
- public void onReceive(final Object message) throws Throwable {
+ public void onReceive(final Object message) {
if (message instanceof ReadActorMessage) {
readAdapter.handle(message, sender(), self());
} else {
}
@Override
- public void onReceive(final Object message) throws Throwable {
+ public void onReceive(final Object message) {
if (message instanceof ReadActorMessage) {
readAdapter.handle(message, sender(), self());
} else if (message instanceof WriteActorMessage) {
}
@Override
- public void onReceive(final Object message) throws Throwable {
+ public void onReceive(final Object message) {
if (message instanceof WriteActorMessage) {
writeAdapter.handle(message, sender(), context(), self());
} else if (message instanceof ReceiveTimeout) {
import com.google.common.util.concurrent.SettableFuture;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.controller.md.sal.common.api.MappingCheckedFuture;
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.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
* 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.topology.singleton.impl.tx;
import akka.actor.ActorRef;
import java.util.function.Consumer;
import javax.annotation.concurrent.GuardedBy;
import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.controller.md.sal.common.api.MappingCheckedFuture;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncWriteTransaction;
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.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
return false;
}
- processTransactionOperation(facade -> facade.cancel());
+ processTransactionOperation(AsyncWriteTransaction::cancel);
return true;
}
}
@Override
- public void close() throws Exception {
+ public void close() {
if (communicator != null) {
communicator.close();
}
package org.opendaylight.netconf.topology.singleton.messages;
import java.io.Externalizable;
-import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.datastore.node.utils.stream.SerializationUtils;
}
@Override
- public void writeExternal(final ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) {
SerializationUtils.serializePathAndNode(getIdentifier(), node, out);
}
@Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) {
SerializationUtils.deserializePathAndNode(in, this, APPLIER);
}
import org.opendaylight.controller.md.sal.dom.broker.impl.mount.DOMMountPointServiceImpl;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionListener;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
+import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
+import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
import org.opendaylight.mdsal.eos.dom.simple.SimpleDOMEntityOwnershipService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
@Mock private ScheduledThreadPool mockKeepaliveExecutor;
@Mock private ActorSystemProvider mockMasterActorSystemProvider;
- @Mock private MountProvisionListener masterMountPointListener;
+ @Mock private DOMMountPointListener masterMountPointListener;
private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
@Mock private ActorSystemProvider mockSlaveActorSystemProvider;
@Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
@Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
- @Mock private MountProvisionListener slaveMountPointListener;
+ @Mock private DOMMountPointListener slaveMountPointListener;
private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
private DataBroker slaveDataBroker;
private ActorSystem slaveSystem;
mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
masterMountPointService, mockEncryptionService) {
@Override
- protected NetconfTopologyContext newNetconfTopologyContext(NetconfTopologySetup setup,
- ServiceGroupIdentifier serviceGroupIdent, Timeout actorResponseWaitTime) {
+ protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
+ final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime) {
NetconfTopologyContext context =
super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime);
NetconfTopologyContext spiedContext = spy(context);
slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
- slaveMountPointService, mockEncryptionService) {
+ slaveMountPointService, mockEncryptionService) {
@Override
- protected NetconfTopologyContext newNetconfTopologyContext(NetconfTopologySetup setup,
- ServiceGroupIdentifier serviceGroupIdent, Timeout actorResponseWaitTime) {
+ protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
+ final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime) {
NetconfTopologyContext spiedContext =
spy(super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime));
slaveNetconfTopologyContextFuture.set(spiedContext);
slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
@Override
- public void onTransactionChainSuccessful(TransactionChain<?, ?> chain) {
+ public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
}
@Override
- public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction,
- Throwable cause) {
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
LOG.error("Slave transaction chain failed", cause);
}
});
verify(mockSlaveClusterSingletonServiceReg).close();
}
- private void testDOMRpcService(DOMRpcService domRpcService)
+ private void testDOMRpcService(final DOMRpcService domRpcService)
throws InterruptedException, ExecutionException, TimeoutException {
testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
testPutTopRpc(domRpcService, null);
testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
}
- private void testPutTopRpc(DOMRpcService domRpcService, DOMRpcResult result)
+ private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
throws InterruptedException, ExecutionException, TimeoutException {
ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
}
- private void testGetTopRpc(DOMRpcService domRpcService, DOMRpcResult result)
+ private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
throws InterruptedException, ExecutionException, TimeoutException {
testRpc(domRpcService, getTopRpcSchemaPath, null, result);
}
- private void testRpc(DOMRpcService domRpcService, SchemaPath schemaPath, NormalizedNode<?, ?> input,
- DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
+ private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
+ final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
+ ExecutionException, TimeoutException {
final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, Futures.immediateCheckedFuture(result));
if (result == null) {
assertNull(actual);
}
}
- private void testFailedRpc(DOMRpcService domRpcService, SchemaPath schemaPath, NormalizedNode<?, ?> input)
- throws InterruptedException, TimeoutException {
+ private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
+ final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
try {
invokeRpc(domRpcService, schemaPath, input, Futures.immediateFailedCheckedFuture(
new ClusteringRpcException("mock")));
}
}
- private DOMRpcResult invokeRpc(DOMRpcService domRpcService, SchemaPath schemaPath, NormalizedNode<?, ?> input,
- CheckedFuture<DOMRpcResult, DOMRpcException> returnFuture)
+ private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
+ final NormalizedNode<?, ?> input, final CheckedFuture<DOMRpcResult, DOMRpcException> returnFuture)
throws InterruptedException, ExecutionException, TimeoutException {
topRpcImplementation.init(returnFuture);
final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
return resultFuture.get(5, TimeUnit.SECONDS);
}
- private static void testDOMDataBrokerOperations(DOMDataBroker dataBroker)
+ private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
throws InterruptedException, ExecutionException, TimeoutException {
DOMDataWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
assertTrue(readTx.cancel());
}
- private static void writeNetconfNode(String cacheDir, DataBroker databroker)
+ private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
throws InterruptedException, ExecutionException, TimeoutException {
final NetconfNode netconfNode = new NetconfNodeBuilder()
.setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
writeTx.commit().get(5, TimeUnit.SECONDS);
}
- private static void verifyDataInStore(DOMDataReadTransaction readTx, YangInstanceIdentifier path,
- NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
+ private static void verifyDataInStore(final DOMDataReadTransaction readTx, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
.get(5, TimeUnit.SECONDS);
assertTrue(read.isPresent());
assertTrue(exists);
}
- private static void verifyTopologyNodesCreated(DataBroker dataBroker) {
+ private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
await().atMost(5, TimeUnit.SECONDS).until(() -> {
try (ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction()) {
Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
return dataBrokerTest;
}
- private void awaitMountPointNotPresent(DOMMountPointService mountPointService) {
+ private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
await().atMost(5, TimeUnit.SECONDS).until(
() -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
}
- private static DOMDataBroker getDOMDataBroker(DOMMountPoint mountPoint) {
+ private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
return getMountPointService(mountPoint, DOMDataBroker.class);
}
- private static DOMRpcService getDOMRpcService(DOMMountPoint mountPoint) {
+ private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
return getMountPointService(mountPoint, DOMRpcService.class);
}
- private static <T extends DOMService> T getMountPointService(DOMMountPoint mountPoint, Class<T> serviceClass) {
+ private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
+ final Class<T> serviceClass) {
final Optional<T> maybeService = mountPoint.getService(serviceClass);
assertTrue(maybeService.isPresent());
return maybeService.get();
}
- private DOMMountPoint awaitMountPoint(DOMMountPointService mountPointService) {
+ private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
await().atMost(5, TimeUnit.SECONDS).until(() -> {
return mountPointService.getMountPoint(yangNodeInstanceId).isPresent();
});
return mountPointService.getMountPoint(yangNodeInstanceId).get();
}
- private RpcDefinition findRpcDefinition(String rpc) {
+ private RpcDefinition findRpcDefinition(final String rpc) {
Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
RpcDefinition rpcDefinition = null;
for (RpcDefinition def: topModule.getRpcs()) {
private volatile CheckedFuture<DOMRpcResult, DOMRpcException> returnFuture;
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(DOMRpcIdentifier rpc,
- NormalizedNode<?, ?> input) {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final DOMRpcIdentifier rpc,
+ final NormalizedNode<?, ?> input) {
rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
return returnFuture;
}
- void init(CheckedFuture<DOMRpcResult, DOMRpcException> retFuture) {
+ void init(final CheckedFuture<DOMRpcResult, DOMRpcException> retFuture) {
this.returnFuture = retFuture;
rpcInvokedFuture = SettableFuture.create();
}
- void verify(DOMRpcIdentifier expRpc, NormalizedNode<?, ?> expInput)
+ void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
throws InterruptedException, ExecutionException, TimeoutException {
final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
assertEquals(expRpc, actual.getKey());
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
- public void handleReceive(Object message) throws Exception {
+ public void handleReceive(Object message) {
CompletableFuture dropFuture = messagesToDrop.remove(message.getClass());
if (dropFuture != null) {
dropFuture.complete(message);
* 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.topology.singleton.impl;
import static org.awaitility.Awaitility.await;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
public class NetconfTopologyManagerTest {
private static final int ACTOR_RESPONSE_WAIT_TIME = 10;
<dependency>
<groupId>org.opendaylight.aaa</groupId>
<artifactId>aaa-encrypt-service</artifactId>
- <version>0.8.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
}
@Override
- public void close() throws Exception {
+ public void close() {
// close all existing connectors, delete whole topology in datastore?
for (final NetconfConnectorDTO connectorDTO : activeConnectors.values()) {
connectorDTO.close();
}
}
- public static Collection<String> extractCapabilitiesFromHello(final Document doc)
- throws NetconfDocumentedException {
+ public static Collection<String> extractCapabilitiesFromHello(final Document doc) {
XmlElement responseElement = XmlElement.fromDomDocument(doc);
// Extract child element <capabilities> from <hello> with or without(fallback) the same namespace
Optional<XmlElement> capabilitiesElement = responseElement
}
@Override
- public void operationComplete(final ChannelFuture channelFuture) throws Exception {
+ public void operationComplete(final ChannelFuture channelFuture) {
Preconditions.checkState(channelFuture.isSuccess(), "Unable to send exception %s", sendErrorException,
channelFuture.cause());
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-generator-impl</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller.model</groupId>
- <artifactId>model-inventory</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>ietf-topology</artifactId>
<groupId>org.opendaylight.mdsal.model</groupId>
<artifactId>ietf-inet-types-2013-07-15</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal.model</groupId>
+ <artifactId>yang-ext</artifactId>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
<dependency>
} catch (final IOException e) {
LOG.warn("Unable to download yang library from {}", url, e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
}
} catch (final ExecutionException e) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
MODULES_STATE_MODULE_LIST, e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
if (moduleListNodeResult.getErrors().isEmpty() == false) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
}
LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
} catch (final IOException e) {
LOG.warn("Unable to download yang library from {}", url, e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
}
contentType.equals("application/json") ? readJson(in) : readXml(in);
if (!optionalModulesStateNode.isPresent()) {
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
return new LibraryModulesSchemas(schemasMapping.build());
} catch (final IOException e) {
LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return new LibraryModulesSchemas(Collections.emptyMap());
}
}
: QName.create(URI.create(moduleNameSpace), moduleName);
try {
- return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
+ return Optional.of(new AbstractMap.SimpleImmutableEntry<>(
moduleQName, new URL(schemaUriAsString.get())));
} catch (final MalformedURLException e) {
LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
}
@Override
- public DeviceSources call() throws Exception {
+ public DeviceSources call() {
final NetconfDeviceSchemas availableSchemas =
stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
- public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.<RemoteYangSchema>emptySet());
+ public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.emptySet());
private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
final RemoteDeviceId id,
final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
final int rpcMessageLimit) {
- this(id, remoteDevice, Optional.<UserPreferences>absent(), rpcMessageLimit);
+ this(id, remoteDevice, Optional.absent(), rpcMessageLimit);
}
private NetconfDeviceCommunicator(
}
- public void close() throws Exception {
+ @Override
+ public void close() {
mountInstance.close();
if (topologyDatastoreAdapter != null) {
topologyDatastoreAdapter.close();
}
}
- public static final class MountInstance implements AutoCloseable {
+ public static class MountInstance implements AutoCloseable {
private final DOMMountPointService mountService;
private final RemoteDeviceId id;
private ObjectRegistration<DOMMountPoint> topologyRegistration;
- public MountInstance(final DOMMountPointService mountService, final RemoteDeviceId id) {
+ MountInstance(final DOMMountPointService mountService, final RemoteDeviceId id) {
this.mountService = Preconditions.checkNotNull(mountService);
this.id = Preconditions.checkNotNull(id);
}
}
@Override
- public synchronized void close() throws Exception {
+ public synchronized void close() {
onTopologyDeviceDisconnected();
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
+public class NetconfDeviceTopologyAdapter implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
}
final DataContainerChild<?, ?> editStructure =
- netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+ netOps.createEditConfigStrcture(Optional.fromNullable(data),
Optional.of(ModifyAction.REPLACE), path);
- editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "put");
+ editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "put");
}
@Override
}
final DataContainerChild<?, ?> editStructure =
- netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
- Optional.<ModifyAction>absent(), path);
- editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
+ netOps.createEditConfigStrcture(Optional.fromNullable(data),
+ Optional.absent(), path);
+ editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "merge");
}
/**
public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
checkEditable(store);
final DataContainerChild<?, ?> editStructure =
- netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
+ netOps.createEditConfigStrcture(Optional.absent(),
Optional.of(ModifyAction.DELETE), path);
- editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
+ editConfig(path, Optional.absent(),
editStructure, Optional.of(ModifyAction.NONE), "delete");
}
* 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.sal.connect.netconf.sal.tx;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
+import org.opendaylight.controller.md.sal.common.api.MappingCheckedFuture;
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.DOMDataReadOnlyTransaction;
-import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfRpcFutureCallback;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public final class ReadOnlyTx implements DOMDataReadOnlyTransaction {
private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTx.class);
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.ByteArrayInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nonnull;
}
@Override
- public InputStream openStream() throws IOException {
+ public InputStream openStream() {
return new ByteArrayInputStream(schemaString.get().getBytes(StandardCharsets.UTF_8));
}
}
public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
final DataContainerChild<?, ?> editStructure,
final boolean rollback) {
- return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
+ return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.absent(), rollback);
}
public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
final DataContainerChild<?, ?> editStructure,
final boolean rollback) {
- return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
+ return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.absent(), rollback);
}
public ListenableFuture<DOMRpcResult> editConfig(
*/
package org.opendaylight.netconf.sal.connect.netconf.util;
-import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
}
private static Map<QName, DataSchemaNode> asMap(final Collection<DataSchemaNode> childNodes) {
- return Maps.uniqueIndex(childNodes, (Function<DataSchemaNode, QName>) DataSchemaNode::getQName);
+ return Maps.uniqueIndex(childNodes, DataSchemaNode::getQName);
}
@Override
import com.google.common.base.Preconditions;
import java.net.InetSocketAddress;
+import java.util.Objects;
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.HostBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
public final class RemoteDeviceId {
+ private static final String DEFAULT_TOPOLOGY_NAME = TopologyNetconf.QNAME.getLocalName();
+ private static final KeyedInstanceIdentifier<Topology, TopologyKey> DEFAULT_TOPOLOGY_IID =
+ InstanceIdentifier.create(NetworkTopology.class)
+ .child(Topology.class, new TopologyKey(new TopologyId(DEFAULT_TOPOLOGY_NAME)));
+ private static final YangInstanceIdentifier DEFAULT_TOPOLOGY_NODE = YangInstanceIdentifier.builder()
+ .node(NetworkTopology.QNAME).node(Topology.QNAME)
+ .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), DEFAULT_TOPOLOGY_NAME)
+ .node(Node.QNAME)
+ .build();
+ private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "node-id").intern();
private final String name;
- private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier path;
- private final InstanceIdentifier<Node> bindingPath;
private final NodeKey key;
- private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath;
- private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
+ private final YangInstanceIdentifier topologyPath;
+ private final KeyedInstanceIdentifier<Node, NodeKey> topologyBindingPath;
private InetSocketAddress address;
private Host host;
private RemoteDeviceId(final String name) {
this.name = Preconditions.checkNotNull(name);
+ this.topologyPath = DEFAULT_TOPOLOGY_NODE
+ .node(new NodeIdentifierWithPredicates(Node.QNAME, NODE_ID_QNAME, name));
this.key = new NodeKey(new NodeId(name));
- this.path = createBIPath(name);
- this.bindingPath = createBindingPath(key);
- this.topologyPath = createBIPathForTopology(name);
- this.topologyBindingPath = createBindingPathForTopology(key);
+ this.topologyBindingPath = DEFAULT_TOPOLOGY_IID.child(Node.class, key);
}
public RemoteDeviceId(final String name, InetSocketAddress address) {
this.host = buildHost();
}
- private static InstanceIdentifier<Node> createBindingPath(final NodeKey key) {
- return InstanceIdentifier.builder(Nodes.class).child(Node.class, key).build();
- }
-
- private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) {
- final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
- builder.node(Nodes.QNAME).node(Node.QNAME)
- .nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
-
- return builder.build();
- }
-
- private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network
- .topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
- final InstanceIdentifier<NetworkTopology> networkTopology =
- InstanceIdentifier.builder(NetworkTopology.class).build();
- final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology
- .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
- return topology
- .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node.class,
- new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network
- .topology.topology.NodeKey(new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.NodeId(key.getId().getValue())));
- }
-
- private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(
- final String name) {
- final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
- builder
- .node(NetworkTopology.QNAME)
- .node(Topology.QNAME)
- .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"),
- TopologyNetconf.QNAME.getLocalName())
- .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node.QNAME)
- .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node.QNAME,
- QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
- return builder.build();
- }
-
private Host buildHost() {
return HostBuilder.getDefaultInstance(address.getHostString());
}
return name;
}
- public InstanceIdentifier<Node> getBindingPath() {
- return bindingPath;
- }
-
- public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier getPath() {
- return path;
- }
-
public NodeKey getBindingKey() {
return key;
}
- public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
- .network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
+ public InstanceIdentifier<Node> getTopologyBindingPath() {
return topologyBindingPath;
}
if (!(obj instanceof RemoteDeviceId)) {
return false;
}
-
final RemoteDeviceId that = (RemoteDeviceId) obj;
-
- if (!name.equals(that.name)) {
- return false;
- }
- return bindingPath.equals(that.bindingPath);
+ return name.equals(that.name) && topologyBindingPath.equals(that.topologyBindingPath);
}
@Override
public int hashCode() {
- int result = name.hashCode();
- result = 31 * result + bindingPath.hashCode();
- return result;
+ return Objects.hash(name, topologyBindingPath);
}
}
+++ /dev/null
-module netconf-node-inventory {
- namespace "urn:opendaylight:netconf-node-inventory";
- prefix "netinv";
-
- import opendaylight-inventory { prefix inv; revision-date "2013-08-19";}
- import yang-ext {prefix ext; revision-date "2013-07-09";}
-
- revision "2014-01-08" {
- description "Initial revision of Inventory model";
- }
-
- grouping netconf-node-fields {
- status deprecated;
- leaf connected {
- type boolean;
- }
-
- leaf-list initial-capability {
- type string;
- }
-
- leaf-list current-capability {
- type string;
- }
-
- container pass-through {
- when "../connected = true";
- description
- "When the underlying node is connected, its NETCONF context
- is available verbatim under this container through the
- mount extension.";
- }
- }
-
- augment /inv:nodes/inv:node {
- ext:augment-identifier "netconf-node";
- status deprecated;
- uses netconf-node-fields;
- }
-}
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.ModuleImport;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
// Make fallback attempt to fail due to empty resolved sources
final SchemaResolutionException schemaResolutionException
= new SchemaResolutionException("fail first",
- Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
+ Collections.emptyList(), HashMultimap.create());
doReturn(Futures.immediateFailedFuture(schemaResolutionException))
.when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
import java.util.List;
import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class,
- NetconfSessionPreferences.class})
public class NetconfDeviceSalFacadeTest {
private NetconfDeviceSalFacade deviceFacade;
+ @Mock
private NetconfDeviceTopologyAdapter netconfDeviceTopologyAdapter;
+ @Mock
private NetconfDeviceSalProvider.MountInstance mountInstance;
@Mock
deviceFacade = new NetconfDeviceSalFacade(remoteDeviceId, salProvider);
- netconfDeviceTopologyAdapter = PowerMockito.mock(NetconfDeviceTopologyAdapter.class);
- mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
-
doReturn(netconfDeviceTopologyAdapter).when(salProvider).getTopologyDatastoreAdapter();
doNothing().when(netconfDeviceTopologyAdapter)
.updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
import static org.opendaylight.mdsal.common.api.CommitInfo.emptyFluentFuture;
import com.google.common.base.Optional;
-import com.google.common.util.concurrent.MoreExecutors;
import java.net.InetSocketAddress;
-import java.util.EnumMap;
import java.util.concurrent.TimeUnit;
-import javassist.ClassPool;
+import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
-import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+import org.opendaylight.controller.md.sal.binding.test.ConcurrentDataBrokerTestCustomizer;
import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-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.spi.data.DOMStore;
-import org.opendaylight.mdsal.binding.dom.codec.gen.impl.DataObjectSerializerGenerator;
-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.GeneratedClassLoadingStrategy;
-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.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class NetconfDeviceTopologyAdapterTest {
private final RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
- @Mock
- private DataBroker broker;
@Mock
private WriteTransaction writeTx;
@Mock
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- doReturn(txChain).when(broker).createTransactionChain(any(TransactionChainListener.class));
doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
doNothing().when(writeTx)
.put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
"/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang",
"/schemas/network-topology-augment-test@2016-08-08.yang");
schemaContext.getModules();
- final DOMSchemaService schemaService = createSchemaService();
-
- final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
- final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
-
- final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
- datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
- datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
-
- domDataBroker = new SerializedDOMDataBroker(datastores, MoreExecutors.newDirectExecutorService());
-
- final ClassPool pool = ClassPool.getDefault();
- final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
- final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
- final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- codecRegistry.onBindingRuntimeContextUpdated(
- BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
- final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
- final BindingToNormalizedNodeCodec bindingToNormalized =
- new BindingToNormalizedNodeCodec(loading, codecRegistry);
- bindingToNormalized.onGlobalContextUpdated(schemaContext);
- dataBroker = new BindingDOMDataBrokerAdapter(domDataBroker, bindingToNormalized);
+ ConcurrentDataBrokerTestCustomizer customizer = new ConcurrentDataBrokerTestCustomizer(true);
+ domDataBroker = customizer.getDOMDataBroker();
+ dataBroker = customizer.createDataBroker();
+ customizer.updateSchema(schemaContext);
transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
@Override
adapter = new NetconfDeviceTopologyAdapter(id, transactionChain); //not a mock
adapter.setDeviceAsFailed(null);
- Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL,
- id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
-
- assertEquals("Netconf node should be presented.", true, netconfNode.isPresent());
- assertEquals("Connection status should be failed.",
- NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(),
- netconfNode.get().getConnectionStatus().getName());
-
+ Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> {
+ Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction()
+ .read(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class))
+ .checkedGet(5, TimeUnit.SECONDS);
+ return netconfNode.isPresent() && netconfNode.get().getConnectionStatus()
+ == NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect;
+ });
}
@Test
dataTestId, testNode.get().getValue());
}
- private DOMSchemaService createSchemaService() {
- return new DOMSchemaService() {
-
- @Override
- public SchemaContext getSessionContext() {
- return schemaContext;
- }
-
- @Override
- public SchemaContext getGlobalContext() {
- return schemaContext;
- }
-
- @Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
- final SchemaContextListener listener) {
- listener.onGlobalContextUpdated(getGlobalContext());
- return new AbstractListenerRegistration<SchemaContextListener>(listener) {
- @Override
- protected void removeRegistration() {
- // No-op
- }
- };
- }
- };
- }
-
@Test
public void testRemoveDeviceConfiguration() throws Exception {
doReturn(emptyFluentFuture()).when(writeTx).commit();
import org.opendaylight.yangtools.util.xml.UntrustedXML;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- final DOMRpcResult value = new DefaultDOMRpcResult(getNode(), Collections.<RpcError>emptySet());
+ final DOMRpcResult value = new DefaultDOMRpcResult(getNode(), Collections.emptySet());
CheckedFuture<DOMRpcResult, DOMRpcException> response = Futures.immediateCheckedFuture(value);
doReturn(response).when(service).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class NetconfMessageTransformerTest {
assertNotNull(compositeNodeRpcResult.getResult());
final DOMSource schemaContent =
((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
- assertThat(((Element) schemaContent.getNode()).getTextContent(),
+ assertThat(schemaContent.getNode().getTextContent(),
CoreMatchers.containsString("Random YANG SCHEMA"));
}
.nodeWithKey(Schema.QNAME, keys).build();
final DataContainerChild<?, ?> editConfigStructure =
createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id,
- Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
+ Optional.absent(), Optional.fromNullable(schemaNode));
final DataContainerChild<?, ?> target = NetconfBaseOps.getTargetNode(NETCONF_CANDIDATE_QNAME);
+<?xml version="1.0"?>
<modules-are-note-here xmlns="urn:ietf:params:xml:ns:yang:ietf-yang-library">
<module-set-id>21429371628890</module-set-id>
-</modules-are-note-here>
\ No newline at end of file
+</modules-are-note-here>
}
@Override
- public Response onCompleted(Response response) throws Exception {
+ public Response onCompleted(Response response) {
semaphore.release();
return response;
}
}
@Override
- public Void call() throws Exception {
+ public Void call() {
if (invokeAsync) {
this.invokeAsync();
} else {
package org.opendaylight.netconf.test.tool;
+import com.google.common.collect.ClassToInstanceMap;
+import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.MoreExecutors;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
+import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
import org.opendaylight.netconf.api.capability.Capability;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.impl.SessionIdProvider;
@Override
public AutoCloseable registerCapabilityListener(
final CapabilityListener listener) {
- listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
+ listener.onCapabilitiesChanged(caps, Collections.emptySet());
return () -> {
};
}
final DiscardChanges discardChanges = new DiscardChanges(
String.valueOf(currentSessionId), transactionProvider);
- return Sets.<NetconfOperation>newHashSet(get, getConfig,
+ return Sets.newHashSet(get, getConfig,
editConfig, commit, lock, unLock, discardChanges);
}
}
};
}
+
+ @Override
+ public ClassToInstanceMap<DOMSchemaServiceExtension> getExtensions() {
+ return ImmutableClassToInstanceMap.of();
+ }
};
}
}
}
private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
- final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) throws IOException {
+ final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) {
return new SshProxyServerConfigurationBuilder()
.setBindingAddress(bindingAddress)
.setLocalAddress(tcpLocalAddress)
}
@Override
- public InputStream openStream() throws IOException {
+ public InputStream openStream() {
return getClass().getResourceAsStream(resource);
}
}), PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
private static class TimeoutGuard implements Callable<Void> {
@Override
- public Void call() throws Exception {
+ public Void call() {
resultsLog.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
root.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
System.exit(0);
}
@Override
- public T call() throws Exception {
+ public T call() {
try {
return theCallable.call();
} catch (Exception e) {
@Override
public AutoCloseable registerCapabilityListener(
final CapabilityListener listener) {
- listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
+ listener.onCapabilitiesChanged(caps, Collections.emptySet());
return () -> {
};
}
}
@Override
- public Response onCompleted(Response response) throws Exception {
+ public Response onCompleted(Response response) {
semaphore.release();
return response;
}
}
@Override
- public Void call() throws Exception {
+ public Void call() {
executionStrategy.invoke();
asyncHttpClient.closeAsynchronously();
return null;
}
- public static void main(String[] args) throws IOException {
+ public static void main(String[] args) {
Parameters parameters = parseArgs(args, Parameters.getParser());
parameters.validate();
}
@Override
- public Boolean call() throws Exception {
+ public Boolean call() {
executionStrategy.invoke();
netconfClientSession.close();
return Boolean.TRUE;
import com.google.common.collect.ImmutableSet;
import java.io.File;
-import java.security.PublicKey;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
-import org.apache.sshd.server.session.ServerSession;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.auth.AuthProvider;
import org.opendaylight.netconf.test.tool.operations.OperationsCreator;
return true;
};
- public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = new PublickeyAuthenticator() {
- @Override
- public boolean authenticate(final String username, final PublicKey key, final ServerSession session) {
- LOG.info("Auth with public key: {}", key);
- return true;
- }
+ public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = (username, key, session) -> {
+ LOG.info("Auth with public key: {}", key);
+ return true;
};
private int generateConfigsTimeout = (int) TimeUnit.MINUTES.toMillis(30);
}
@Override
- public HandlingPriority canHandle(final Document message) throws DocumentedException {
+ public HandlingPriority canHandle(final Document message) {
return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1000);
}
@Override
public AutoCloseable registerCapabilityListener(
final CapabilityListener listener) {
- listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
+ listener.onCapabilitiesChanged(caps, Collections.emptySet());
return () -> {
};
}
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
@Override
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
long delayAggregator = 0;
for (final Map.Entry<Notification, NetconfMessage> notification : notifications.entrySet()) {
}, delayAggregator, TimeUnit.SECONDS);
}
}
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
private static NetconfMessage parseNetconfNotification(String content) {
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
storage.setConfigList(configElementData.getChildElements());
}
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
@Override
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
final Element element = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
for (final XmlElement e : storage.getConfigList()) {
import java.io.File;
import java.io.IOException;
import java.util.List;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
final Element element = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.absent());
for (final XmlElement e : storage.getConfigList()) {
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
package org.opendaylight.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-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;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
- throws DocumentedException {
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) {
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
@Override
}
@Override
- public HandlingPriority canHandle(final Document message) throws DocumentedException {
+ public HandlingPriority canHandle(final Document message) {
return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1000);
}
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
}
@Override
- public InputStream openStream() throws IOException {
+ public InputStream openStream() {
return TestToolUtils.getDataAsStream(cachedSource);
}
};
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-module-junit4</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@Override
public Set<Object> getSingletons() {
- return Collections.<Object>singleton(this.yangLibService);
+ return Collections.singleton(this.yangLibService);
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>mockito-configuration</artifactId>
- <version>2.0.7</version>
+ <version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
}
@Override
- public void operationComplete(final ChannelFuture cf) throws Exception {
+ public void operationComplete(final ChannelFuture cf) {
synchronized (lock) {
LOG.debug("Promise {} connection resolved", lock);
}
@Override
- public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
+ public void channelInactive(final ChannelHandlerContext ctx) {
// This is the ultimate channel inactive handler, not forwarding
if (promise.isCancelled()) {
return;
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
}
private List<V> getValues(K key) {
- List<V> list = store.get(key);
- if (list == null) {
- list = new LinkedList<>();
- store.put(key, list);
- }
-
- return list;
+ return store.computeIfAbsent(key, k -> new LinkedList<>());
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
*/
package org.opendaylight.netconf.md.sal.rest.schema;
-import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Override
public void writeTo(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
- WebApplicationException {
+ final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws
+ WebApplicationException {
try {
YinExportUtils.writeModuleAsYinText(context.getModule(), entityStream);
} catch (final XMLStreamException e) {
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
- WebApplicationException {
+ final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws
+ WebApplicationException {
try {
return readFrom(getInstanceIdentifierContext(), entityStream, isPost());
} catch (final Exception e) {
public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
return readFrom(getInstanceIdentifierContext(), entityStream);
} catch (final Exception e) {
package org.opendaylight.netconf.sal.rest.impl;
-import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
public void writeTo(final PatchStatusContext patchStatusContext, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
final XMLStreamWriter xmlWriter =
}
private static void writeDocument(final XMLStreamWriter writer, final PatchStatusContext context)
- throws XMLStreamException, IOException {
+ throws XMLStreamException {
writer.writeStartElement("", "yang-patch-status", "urn:ietf:params:xml:ns:yang:ietf-yang-patch");
writer.writeStartElement("patch-id");
writer.writeCharacters(context.getPatchId());
}
private static void reportErrors(final List<RestconfError> errors, final XMLStreamWriter writer)
- throws IOException, XMLStreamException {
+ throws XMLStreamException {
writer.writeStartElement("errors");
for (final RestconfError restconfError : errors) {
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
- WebApplicationException {
+ final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws
+ WebApplicationException {
try {
return readFrom(entityStream);
} catch (final RestconfDocumentedException e) {
public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
- final Object nodeVal = ((LeafNode<?>) child).getValue();
+ final Object nodeVal = child.getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (keys.contains(child.getNodeType())) {
- leafBuilder.withValue(((LeafNode<?>) child).getValue());
+ leafBuilder.withValue(child.getValue());
builder.withChild(leafBuilder.build());
} else {
if (trim) {
if (defaultVal == null || !defaultVal.equals(nodeVal)) {
- leafBuilder.withValue(((LeafNode<?>) child).getValue());
+ leafBuilder.withValue(child.getValue());
builder.withChild(leafBuilder.build());
}
} else {
if (defaultVal != null && defaultVal.equals(nodeVal)) {
- leafBuilder.withValue(((LeafNode<?>) child).getValue());
+ leafBuilder.withValue(child.getValue());
builder.withChild(leafBuilder.build());
}
}
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
- final Object nodeVal = ((LeafNode<?>) child).getValue();
+ final Object nodeVal = child.getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (trim) {
if (defaultVal == null || !defaultVal.equals(nodeVal)) {
- leafBuilder.withValue(((LeafNode<?>) child).getValue());
+ leafBuilder.withValue(child.getValue());
builder.withChild(leafBuilder.build());
}
} else {
if (defaultVal != null && defaultVal.equals(nodeVal)) {
- leafBuilder.withValue(((LeafNode<?>) child).getValue());
+ leafBuilder.withValue(child.getValue());
builder.withChild(leafBuilder.build());
}
}
public static ControllerContext newInstance(DOMSchemaService schemaService, DOMMountPointService mountService,
DOMSchemaService domSchemaService) {
- final DOMYangTextSourceProvider yangTextSourceProvider =
- (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions().get(DOMYangTextSourceProvider.class);
+ final DOMYangTextSourceProvider yangTextSourceProvider = domSchemaService.getExtensions()
+ .getInstance(DOMYangTextSourceProvider.class);
return new ControllerContext(schemaService, mountService, yangTextSourceProvider);
}
return childByQName((Module) container, name);
} else {
throw new IllegalArgumentException("Unhandled parameter types: "
- + Arrays.<Object>asList(container, name).toString());
+ + Arrays.asList(container, name).toString());
}
}
private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
final boolean returnJustMountPoint) {
- Preconditions.<List<String>>checkNotNull(strings);
+ Preconditions.checkNotNull(strings);
if (parentNode == null) {
return null;
public void start() {
this.webSocketServerThread = new Thread(WebSocketServer.createInstance(
- new String(websocketAddress.getValue()), websocketPort.getValue()));
+ websocketAddress.stringValue(), websocketPort.getValue()));
this.webSocketServerThread.setName("Web socket server on port " + websocketPort);
this.webSocketServerThread.start();
}
@Override
- public final void close() throws Exception {
+ public final void close() {
this.registration.close();
this.registration = null;
unregister();
* Type of the event.
*/
enum EventType {
- REGISTER, DEREGISTER, NOTIFY;
+ REGISTER, DEREGISTER, NOTIFY
}
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;
-import java.io.IOException;
import java.util.List;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
private WebSocketServerHandshaker handshaker;
@Override
- protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
+ protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
* @param req
* FullHttpRequest
*/
- private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
+ private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
* @param frame
* {@link WebSocketFrame}
*/
- private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
+ private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
if (frame instanceof CloseWebSocketFrame) {
this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
}
@Override
- public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
+ public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
ctx.close();
}
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
- protected void initChannel(final SocketChannel ch) throws Exception {
+ protected void initChannel(final SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec-http", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableClassToInstanceMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
DOMSchemaService mockSchemaService = mock(DOMSchemaService.class);
doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
+ doReturn(ImmutableClassToInstanceMap.of()).when(mockSchemaService).getExtensions();
DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
+ doReturn(ImmutableClassToInstanceMap.of()).when(mockDomSchemaService).getExtensions();
return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
}
import java.io.File;
import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import javax.ws.rs.WebApplicationException;
try {
normalizedNodeContext = this.jsonBodyReader.readFrom(null, null, null,
this.mediaType, null, inputStream);
- } catch (WebApplicationException | IOException e) {
+ } catch (WebApplicationException e) {
// TODO Auto-generated catch block
}
fail("Expected an exception to be thrown.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
- Optional.<String>absent(), Optional.<String>absent());
+ Optional.absent(), Optional.absent());
}
}
fail("Expected an exception to be thrown.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
- Optional.<String>absent());
+ Optional.absent());
verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
Optional.of("app-tag"));
}
fail("Expected an exception");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
- Optional.<String>absent(), Optional.<String>absent());
+ Optional.absent(), Optional.absent());
}
}
fail("Expected an exception");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
- Optional.<String>absent(), Optional.<String>absent());
+ Optional.absent(), Optional.absent());
}
}
fail("Expected an exception.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
- Optional.<String>absent(), Optional.<String>absent());
+ Optional.absent(), Optional.absent());
}
}
final String uriPath = "toaster:cancel-toast";
- final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
+ final Optional<String> output = this.service.invokeRpc(uriPath, Optional.absent());
assertEquals("Output present", false, output.isPresent());
final String uriPath = "toaster:testOutput";
- final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
+ final Optional<String> output = this.service.invokeRpc(uriPath, Optional.absent());
assertEquals("Output present", true, output.isPresent());
assertNotNull("Returned null response", output.get());
final String uriPath = "toaster:cancel-toast";
- this.service.invokeRpc(uriPath, Optional.<String>absent());
+ this.service.invokeRpc(uriPath, Optional.absent());
}
void testGet(final LogicalDatastoreType datastoreType) throws OperationFailedException {
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.api.Draft02;
public void createConfigurationDataNullTest() throws UnsupportedEncodingException {
when(brokerFacade.commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class),
any(NormalizedNode.class), Mockito.anyString(), Mockito.anyString()))
- .thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
+ .thenReturn(Futures.immediateCheckedFuture(null));
//FIXME : find who is set schemaContext
// final String URI_1 = "/config";
final PutResult result = Mockito.mock(PutResult.class);
final CheckedFuture<Void, TransactionCommitFailedException> checkedFuture =
Futures.immediateCheckedFuture(null);
- Mockito.when(this.brokerFacade.commitConfigurationDataPut(this.schemaContext, yii, data, null, null))
+ Mockito.when(this.brokerFacade.commitConfigurationDataPut(schemaContext, yii, data, null, null))
.thenReturn(result);
Mockito.when(result.getFutureOfPutData()).thenReturn(checkedFuture);
Mockito.when(result.getStatus()).thenReturn(Status.OK);
import com.google.common.collect.Iterables;
import com.google.gson.stream.JsonReader;
-import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
return readFrom(path, entityStream, isPost());
} catch (final Exception e) {
}
public static NormalizedNodeContext readFrom(
- final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost)
- throws IOException {
+ final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost) {
final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
return parse(path,doc);
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
return readFrom(path, entityStream);
} catch (final Exception e) {
package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
-import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
public void writeTo(final PatchStatusContext patchStatusContext, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
final XMLStreamWriter xmlWriter =
}
private static void writeDocument(final XMLStreamWriter writer, final PatchStatusContext context)
- throws XMLStreamException, IOException {
+ throws XMLStreamException {
writer.writeStartElement("", "yang-patch-status", "urn:ietf:params:xml:ns:yang:ietf-yang-patch");
writer.writeStartElement("patch-id");
writer.writeCharacters(context.getPatchId());
}
private static void reportErrors(final List<RestconfError> errors, final XMLStreamWriter writer)
- throws IOException, XMLStreamException {
+ throws XMLStreamException {
writer.writeStartElement("errors");
for (final RestconfError restconfError : errors) {
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
- throws IOException, WebApplicationException {
+ throws WebApplicationException {
try {
final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
return parse(path, doc);
*/
package org.opendaylight.restconf.nb.rfc8040.jersey.providers.schema;
-import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Override
public void writeTo(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
- WebApplicationException {
+ final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws
+ WebApplicationException {
try {
YinExportUtils.writeModuleAsYinText(context.getModule(), entityStream);
} catch (final XMLStreamException e) {
protected abstract T emptyBody(InstanceIdentifierContext<?> path);
protected abstract T readBody(InstanceIdentifierContext<?> path, InputStream entityStream)
- throws IOException, WebApplicationException;
+ throws WebApplicationException;
private String getIdentifier() {
}
final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
- try {
- return JsonNormalizedNodeBodyReader.readFrom(instanceIdentifierContext, entityStream, isPost);
- } catch (final IOException e) {
- propagateExceptionAs(uriPath, e, "GET");
- return null;
- }
+ return JsonNormalizedNodeBodyReader.readFrom(instanceIdentifierContext, entityStream, isPost);
}
private String toJson(final PatchStatusContext patchStatusContext) throws IOException {
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
- for (final MapEntryNode child : ((MapNode) payload).getValue()) {
+ for (final MapEntryNode child : payload.getValue()) {
final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
writeTx.put(datastore, childPath, child);
}
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
- final Object nodeVal = ((LeafNode<?>) child).getValue();
+ final Object nodeVal = child.getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (keys.contains(child.getNodeType())) {
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
- final Object nodeVal = ((LeafNode<?>) child).getValue();
+ final Object nodeVal = child.getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (trim) {
final DOMSchemaService domSchemaService) {
RestconfOperationsService restconfOpsService =
new RestconfOperationsServiceImpl(schemaCtxHandler, domMountPointServiceHandler);
- final DOMYangTextSourceProvider yangTextSourceProvider =
- (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions()
- .get(DOMYangTextSourceProvider.class);
+ final DOMYangTextSourceProvider yangTextSourceProvider = domSchemaService.getExtensions()
+ .getInstance(DOMYangTextSourceProvider.class);
RestconfSchemaService restconfSchemaService =
new RestconfSchemaServiceImpl(schemaCtxHandler, domMountPointServiceHandler,
yangTextSourceProvider);
* Type of the event.
*/
enum EventType {
- REGISTER, DEREGISTER, NOTIFY;
+ REGISTER, DEREGISTER, NOTIFY
}
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;
-import java.io.IOException;
import java.util.List;
import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenerAdapter;
import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
private WebSocketServerHandshaker handshaker;
@Override
- protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
+ protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
* @param req
* FullHttpRequest
*/
- private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
+ private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
* @param frame
* {@link WebSocketFrame}
*/
- private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
+ private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
if (frame instanceof CloseWebSocketFrame) {
this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
}
@Override
- public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
+ public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
ctx.close();
}
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
- protected void initChannel(final SocketChannel ch) throws Exception {
+ protected void initChannel(final SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec-http", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
import static org.mockito.Mockito.verify;
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.Futures;
import java.io.FileNotFoundException;
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
+ doReturn(ImmutableClassToInstanceMap.of()).when(domSchemaService).getExtensions();
+
doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(mockReadOnlyTx).read(
eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class));
final String uriPath = "toaster:cancel-toast";
- final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
+ final Optional<String> output = this.service.invokeRpc(uriPath, Optional.absent());
assertEquals("Output present", false, output.isPresent());
final String uriPath = "toaster:testOutput";
- final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
+ final Optional<String> output = this.service.invokeRpc(uriPath, Optional.absent());
assertEquals("Output present", true, output.isPresent());
assertNotNull("Returned null response", output.get());
final String uriPath = "toaster:cancel-toast";
- this.service.invokeRpc(uriPath, Optional.<String>absent());
+ this.service.invokeRpc(uriPath, Optional.absent());
}
void testGet(final LogicalDatastoreType datastoreType) throws OperationFailedException {
assertNotNull(normNode);
final List<Object> listOfValues = new ArrayList<>();
- for (final DataContainerChild<? extends PathArgument, ?> child : ((ContainerNode) normNode).getValue()) {
+ for (final DataContainerChild<? extends PathArgument, ?> child : normNode.getValue()) {
if (child.getNodeType().equals(MonitoringModule.CONT_CAPABILITES_QNAME)) {
for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : ((ContainerNode) child)
.getValue()) {
for (final DataContainerChild<? extends PathArgument, ?> child : containerNode.getValue()) {
if (child instanceof LeafNode) {
- assertEquals(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, ((LeafNode<?>) child).getNodeType());
+ assertEquals(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, child.getNodeType());
}
if (child instanceof MapNode) {
- assertEquals(IetfYangLibrary.MODULE_QNAME_LIST, ((MapNode) child).getNodeType());
+ assertEquals(IetfYangLibrary.MODULE_QNAME_LIST, child.getNodeType());
for (final MapEntryNode mapEntryNode : ((MapNode) child).getValue()) {
String name = "";
String revision = "";
.getValue()) {
switch (dataContainerChild.getNodeType().getLocalName()) {
case IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF:
- name = String.valueOf(((LeafNode<?>) dataContainerChild).getValue());
+ name = String.valueOf(dataContainerChild.getValue());
break;
case IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF:
- revision = String.valueOf(((LeafNode<?>) dataContainerChild).getValue());
+ revision = String.valueOf(dataContainerChild.getValue());
break;
default :
LOG.info("Unknown local name '{}' of node.",
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>3.1.2</version>
+ <version>3.1.3</version>
<relativePath/>
</parent>
LOG.debug("Adding path: [{}]", resourcePath);
api.setPath(resourcePath.concat(getContent(dataStore)));
- Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
+ Iterable<DataSchemaNode> childSchemaNodes = Collections.emptySet();
if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) {
final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
childSchemaNodes = dataNodeContainer.getChildNodes();
import javax.ws.rs.core.UriInfo;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionListener;
+import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.netconf.sal.rest.doc.impl.BaseYangSwaggerGenerator;
import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class MountPointSwagger implements MountProvisionListener, AutoCloseable {
+public class MountPointSwagger implements DOMMountPointListener, AutoCloseable {
private static final String DATASTORES_REVISION = "-";
private static final String DATASTORES_LABEL = "Datastores";
private final AtomicLong idKey = new AtomicLong(0);
- private ListenerRegistration<MountProvisionListener> registration;
+ private ListenerRegistration<DOMMountPointListener> registration;
- public MountPointSwagger(DOMSchemaService globalSchema, DOMMountPointService mountService,
- BaseYangSwaggerGenerator swaggerGenerator) {
+ public MountPointSwagger(final DOMSchemaService globalSchema, final DOMMountPointService mountService,
+ final BaseYangSwaggerGenerator swaggerGenerator) {
this.globalSchema = Objects.requireNonNull(globalSchema);
this.mountService = Objects.requireNonNull(mountService);
this.swaggerGenerator = Objects.requireNonNull(swaggerGenerator);
final URI namespace = node.getQName().getNamespace();
final Optional<Revision> revision = node.getQName().getRevision();
- Map<Optional<Revision>, Module> revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.get(namespace);
- if (revisionToModule == null) {
- revisionToModule = new HashMap<>();
- NAMESPACE_AND_REVISION_TO_MODULE.put(namespace, revisionToModule);
- }
- Module module = revisionToModule.get(revision);
- if (module == null) {
- module = schemaContext.findModule(namespace, revision).orElse(null);
- revisionToModule.put(revision, module);
- }
+ Map<Optional<Revision>, Module> revisionToModule =
+ NAMESPACE_AND_REVISION_TO_MODULE.computeIfAbsent(namespace, k -> new HashMap<>());
+ Module module =
+ revisionToModule.computeIfAbsent(revision, k -> schemaContext.findModule(namespace, k).orElse(null));
if (module != null) {
return module.getName() + ":" + node.getQName().getLocalName();
}
type='text/css'/>\r
<link href='../../explorer/css/screen.css' media='screen' rel='stylesheet'\r
type='text/css'/>\r
- <link rel="stylesheet" type="text/css" href="../../explorer/css/opendaylight.css">\r
+ <link rel="stylesheet" type="text/css" href="../../explorer/static/opendaylight.css">\r
<link rel="stylesheet" type="text/css"\r
href="../../explorer/css/ui-lightness/jquery-ui-1.10.4.custom.min.css">\r
<script type="text/javascript" src="../../explorer/lib/shred.bundle.js"></script>\r
type='text/css' />\r
<link href='css/screen.css' media='screen' rel='stylesheet'\r
type='text/css' />\r
-<link rel="stylesheet" type="text/css" href="/css/opendaylight.css">\r
+<link rel="stylesheet" type="text/css" href="static/opendaylight.css">\r
<link rel="stylesheet" type="text/css"\r
href="css/ui-lightness/jquery-ui-1.10.4.custom.min.css">\r
<script type="text/javascript" src="lib/shred.bundle.js"></script>\r
import java.net.URL;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
import org.opendaylight.controller.sal.binding.api.BindingAwareConsumer;
+import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
import org.opendaylight.netconf.sal.restconf.broker.SalRemoteServiceBroker;
import org.opendaylight.yangtools.restconf.client.RestconfClientFactory;
import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
import org.opendaylight.yangtools.restconf.client.api.UnsupportedProtocolException;
import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
import org.slf4j.Logger;