<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.netconf</groupId>
<mdsal.model.version>0.12.0-SNAPSHOT</mdsal.model.version>
<netconf.version>1.4.0-SNAPSHOT</netconf.version>
<netconf.connector.version>1.7.0-SNAPSHOT</netconf.connector.version>
- <yangtools.version>1.2.0</yangtools.version>
+ <yangtools.version>2.0.0</yangtools.version>
</properties>
<modules>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>odl-yangtools-yang-data</artifactId>
+ <artifactId>odl-yangtools-data</artifactId>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<features name="odl-netconf-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
<feature name="odl-netconf-netty-util" version="${project.version}">
<feature version="${karaf.version}">ssh</feature>
+ <feature version="[3.0.0,4)">odl-netty-4</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>odl-yangtools-yang-data</artifactId>
- <version>1.2.0</version>
+ <artifactId>odl-yangtools-data</artifactId>
+ <version>2.0.0</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-artifacts</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright © 2017 Red Hat, Inc. and others.
+ ~
+ ~ This program and the accompanying materials are made available under the
+ ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ ~ and is available at http://www.eclipse.org/legal/epl-v10.html
+ -->
+<features name="odl-netconf-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
+ <feature name="odl-restconf-nb-rfc8040-noauth" version="${project.version}">
+ <feature version="[3.0.0,4)">odl-karaf-feat-jetty</feature>
+ <feature version="[3.0.0,4)">odl-netty-4</feature>
+ </feature>
+</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-artifacts</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<configfile finalname="etc/org.opendaylight.restconf.cfg">
mvn:org.opendaylight.netconf/sal-rest-connector-config/${project.version}/cfg/restconf
</configfile>
+ <feature version="[3.0.0,4)">odl-karaf-feat-jetty</feature>
+ <feature version="[3.0.0,4)">odl-netty-4</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<artifactId>features-restconf-aggregator</artifactId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>odl-yangtools-yang-data</artifactId>
- <version>1.2.0</version>
+ <artifactId>odl-yangtools-data</artifactId>
+ <version>2.0.0</version>
<type>xml</type>
<classifier>features</classifier>
</dependency>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright © 2018 Red Hat, Inc. and others.
+ ~
+ ~ This program and the accompanying materials are made available under the
+ ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ ~ and is available at http://www.eclipse.org/legal/epl-v10.html
+ -->
+<features name="odl-netconf-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
+ <feature name="odl-yanglib" version="${project.version}">
+ <feature version="[3.0.0,4)">odl-karaf-feat-jetty</feature>
+ </feature>
+</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>karaf4-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.netconf</groupId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigInteger;
+import java.security.GeneralSecurityException;
import java.security.KeyFactory;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
+import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
-import org.apache.sshd.common.util.Base64;
-import org.apache.sshd.common.util.SecurityUtils;
+import org.apache.sshd.common.util.security.SecurityUtils;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.ECPointUtil;
private byte[] bytes = new byte[0];
private int pos = 0;
- public PublicKey decodePublicKey(String keyLine)
- throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
+ public PublicKey decodePublicKey(final String keyLine) throws GeneralSecurityException {
// look for the Base64 encoded part of the line to decode
// both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
- bytes = Base64.decodeBase64(keyLine.getBytes());
+ bytes = Base64.getDecoder().decode(keyLine.getBytes());
if (bytes.length == 0) {
throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
}
throw new IllegalArgumentException("Unknown decode key type " + type + " in " + keyLine);
}
- private PublicKey decodeAsEcDSA()
- throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
+ private PublicKey decodeAsEcDSA() throws GeneralSecurityException {
KeyFactory ecdsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_ECDSA);
ECNamedCurveParameterSpec spec256r1 = ECNamedCurveTable.getParameterSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC);
return ecdsaFactory.generatePublic(pubKeySpec);
}
- private PublicKey decodeAsDSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
+ private PublicKey decodeAsDSA() throws GeneralSecurityException {
KeyFactory dsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_DSA);
BigInteger prime = decodeBigInt();
BigInteger subPrime = decodeBigInt();
return dsaFactory.generatePublic(spec);
}
- private PublicKey decodeAsRSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
+ private PublicKey decodeAsRSA() throws GeneralSecurityException {
KeyFactory rsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_RSA);
BigInteger exponent = decodeBigInt();
BigInteger modulus = decodeBigInt();
}
private int decodeInt() {
- return ((bytes[pos++] & 0xFF) << 24) | ((bytes[pos++] & 0xFF) << 16)
- | ((bytes[pos++] & 0xFF) << 8) | (bytes[pos++] & 0xFF);
+ return (bytes[pos++] & 0xFF) << 24 | (bytes[pos++] & 0xFF) << 16
+ | (bytes[pos++] & 0xFF) << 8 | bytes[pos++] & 0xFF;
}
private BigInteger decodeBigInt() {
return new BigInteger(bigIntBytes);
}
- public static String encodePublicKey(PublicKey publicKey) throws IOException {
+ public static String encodePublicKey(final PublicKey publicKey) throws IOException {
String publicKeyEncoded;
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) {
} else {
throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
}
- publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
+ publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray()));
return publicKeyEncoded;
}
}
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
/**
}
@Override
- protected void applyTo(ClientSession session) {
+ protected void applyTo(final ClientSession session) {
throw new IllegalStateException("Server is not allowed.");
}
};
* @param username Username to be used for authorization
* @return Builder which allows to specify credentials.
*/
- public static final Builder serverAccepted(String sessionName, String username) {
+ public static final Builder serverAccepted(final String sessionName, final String username) {
return new Builder(sessionName, username);
}
private final Set<String> passwords = new HashSet<>();
private final Set<KeyPair> clientKeys = new HashSet<>();
- private Builder(String nodeId, String username) {
+ Builder(final String nodeId, final String username) {
this.nodeId = Preconditions.checkNotNull(nodeId);
this.username = Preconditions.checkNotNull(username);
}
* @param password Password to be used for password-based authorization.
* @return this builder.
*/
- public Builder addPassword(String password) {
+ public Builder addPassword(final String password) {
this.passwords.add(password);
return this;
}
* @param clientKey Keys to be used for authorization.
* @return this builder.
*/
- public Builder addClientKeys(KeyPair clientKey) {
+ public Builder addClientKeys(final KeyPair clientKey) {
this.clientKeys.add(clientKey);
return this;
}
private final Set<String> passwords;
private final Set<KeyPair> clientKeyPair;
- ServerAllowed(String nodeId, String username, Collection<String> passwords,
- Collection<KeyPair> clientKeyPairs) {
+ ServerAllowed(final String nodeId, final String username, final Collection<String> passwords,
+ final Collection<KeyPair> clientKeyPairs) {
this.username = Preconditions.checkNotNull(username);
this.passwords = ImmutableSet.copyOf(passwords);
this.clientKeyPair = ImmutableSet.copyOf(clientKeyPairs);
}
@Override
- protected void applyTo(ClientSession session) {
+ protected void applyTo(final ClientSession session) {
Preconditions.checkArgument(session instanceof ClientSessionImpl);
((ClientSessionImpl) session).setUsername(username);
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.OpenFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
-import org.apache.sshd.common.Session;
import org.apache.sshd.common.future.SshFutureListener;
+import org.apache.sshd.common.session.Session;
import org.opendaylight.netconf.client.NetconfClientSession;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory;
private final InetSocketAddress remoteAddress;
private final PublicKey serverKey;
- CallHomeSessionContext(ClientSession sshSession, CallHomeAuthorization authorization,
- SocketAddress remoteAddress, Factory factory) {
+ CallHomeSessionContext(final ClientSession sshSession, final CallHomeAuthorization authorization,
+ final SocketAddress remoteAddress, final Factory factory) {
this.authorization = Preconditions.checkNotNull(authorization, "authorization");
Preconditions.checkArgument(this.authorization.isServerAllowed(), "Server was not allowed.");
Preconditions.checkArgument(sshSession instanceof ClientSessionImpl,
this.serverKey = this.sshSession.getKex().getServerKey();
}
- static CallHomeSessionContext getFrom(ClientSession sshSession) {
+ static CallHomeSessionContext getFrom(final ClientSession sshSession) {
return sshSession.getAttribute(SESSION_KEY);
}
};
}
- private void channelOpenFailed(Throwable throwable) {
+ private void channelOpenFailed(final Throwable throwable) {
LOG.error("Unable to open netconf subsystem, disconnecting.", throwable);
sshSession.close(false);
}
- private void netconfChannelOpened(ClientChannel netconfChannel) {
+ private void netconfChannelOpened(final ClientChannel netconfChannel) {
nettyChannel = newMinaSshNettyChannel(netconfChannel);
factory.getChannelOpenListener().onNetconfSubsystemOpened(
CallHomeSessionContext.this, this::doActivate);
}
@GuardedBy("this")
- private synchronized Promise<NetconfClientSession> doActivate(NetconfClientSessionListener listener) {
+ private synchronized Promise<NetconfClientSession> doActivate(final NetconfClientSessionListener listener) {
if (activated) {
return newSessionPromise().setFailure(new IllegalStateException("Session already activated."));
}
return activationPromise;
}
- protected MinaSshNettyChannel newMinaSshNettyChannel(ClientChannel netconfChannel) {
+ protected MinaSshNettyChannel newMinaSshNettyChannel(final ClientChannel netconfChannel) {
return new MinaSshNettyChannel(this, sshSession, netconfChannel);
}
- private Promise<NetconfClientSession> newSessionPromise() {
+ private static Promise<NetconfClientSession> newSessionPromise() {
return GlobalEventExecutor.INSTANCE.newPromise();
}
private final CallHomeNetconfSubsystemListener subsystemListener;
private final ConcurrentMap<String, CallHomeSessionContext> sessions = new ConcurrentHashMap<>();
- Factory(EventLoopGroup nettyGroup, NetconfClientSessionNegotiatorFactory negotiatorFactory,
- CallHomeNetconfSubsystemListener subsystemListener) {
+ Factory(final EventLoopGroup nettyGroup, final NetconfClientSessionNegotiatorFactory negotiatorFactory,
+ final CallHomeNetconfSubsystemListener subsystemListener) {
this.nettyGroup = Preconditions.checkNotNull(nettyGroup, "nettyGroup");
this.negotiatorFactory = Preconditions.checkNotNull(negotiatorFactory, "negotiatorFactory");
this.subsystemListener = Preconditions.checkNotNull(subsystemListener);
}
- void remove(CallHomeSessionContext session) {
+ void remove(final CallHomeSessionContext session) {
sessions.remove(session.getSessionName(), session);
}
- ReverseSshChannelInitializer getChannelInitializer(NetconfClientSessionListener listener) {
+ ReverseSshChannelInitializer getChannelInitializer(final NetconfClientSessionListener listener) {
return ReverseSshChannelInitializer.create(negotiatorFactory, listener);
}
}
@Nullable
- CallHomeSessionContext createIfNotExists(ClientSession sshSession, CallHomeAuthorization authorization,
- SocketAddress remoteAddress) {
+ CallHomeSessionContext createIfNotExists(final ClientSession sshSession,
+ final CallHomeAuthorization authorization, final SocketAddress remoteAddress) {
CallHomeSessionContext session = new CallHomeSessionContext(sshSession, authorization,
remoteAddress, this);
CallHomeSessionContext preexisting = sessions.putIfAbsent(session.getSessionName(), session);
import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.EventLoop;
import java.net.SocketAddress;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.session.ClientSession;
import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerReader;
import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerReader.ReadMsgHandler;
import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter;
private volatile boolean nettyClosed = false;
- MinaSshNettyChannel(CallHomeSessionContext context, ClientSession session, ClientChannel sshChannel) {
+ MinaSshNettyChannel(final CallHomeSessionContext context, final ClientSession session,
+ final ClientChannel sshChannel) {
this.context = Preconditions.checkNotNull(context);
this.session = Preconditions.checkNotNull(session);
this.sshChannel = Preconditions.checkNotNull(sshChannel);
private ChannelOutboundHandlerAdapter createChannelAdapter() {
return new ChannelOutboundHandlerAdapter() {
-
@Override
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
+ public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
+ throws Exception {
sshWriteAsyncHandler.write(ctx, msg, promise);
}
-
};
}
return config;
}
- private boolean notClosing(org.apache.sshd.common.Closeable sshCloseable) {
+ private static boolean notClosing(final org.apache.sshd.common.Closeable sshCloseable) {
return !sshCloseable.isClosing() && !sshCloseable.isClosed();
}
}
@Override
- protected boolean isCompatible(EventLoop loop) {
+ protected boolean isCompatible(final EventLoop loop) {
return true;
}
}
@Override
- protected void doBind(SocketAddress localAddress) throws Exception {
+ protected void doBind(final SocketAddress localAddress) throws Exception {
throw new UnsupportedOperationException("Bind not supported.");
}
- void doMinaDisconnect(boolean blocking) {
+ void doMinaDisconnect(final boolean blocking) {
if (notClosing(session)) {
sshChannel.close(blocking);
session.close(blocking);
}
@Override
- protected void doWrite(ChannelOutboundBuffer in) throws Exception {
+ protected void doWrite(final ChannelOutboundBuffer in) throws Exception {
throw new IllegalStateException("Outbound writes to SSH should be done by SSH Write handler");
}
private final class FireReadMessage implements ReadMsgHandler {
@Override
- public void onMessageRead(ByteBuf msg) {
+ public void onMessageRead(final ByteBuf msg) {
pipeline().fireChannelRead(msg);
}
}
}
private class SshUnsafe extends AbstractUnsafe {
-
@Override
- public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
+ public void connect(final SocketAddress remoteAddress, final SocketAddress localAddress,
+ final ChannelPromise promise) {
throw new UnsupportedOperationException("Unsafe is not supported.");
}
}
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.PublicKey;
-import org.apache.sshd.ClientSession;
-import org.apache.sshd.SshClient;
-import org.apache.sshd.client.ServerKeyVerifier;
-import org.apache.sshd.client.SessionFactory;
+import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
-import org.apache.sshd.common.KeyExchange;
-import org.apache.sshd.common.Session;
-import org.apache.sshd.common.SessionListener;
+import org.apache.sshd.client.session.SessionFactory;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoServiceFactory;
import org.apache.sshd.common.io.mina.MinaServiceFactory;
import org.apache.sshd.common.io.nio2.Nio2ServiceFactory;
+import org.apache.sshd.common.kex.KeyExchange;
+import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.session.SessionListener;
import org.opendaylight.netconf.callhome.protocol.CallHomeSessionContext.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final InetSocketAddress bindAddress;
private final StatusRecorder recorder;
- NetconfCallHomeServer(SshClient sshClient, CallHomeAuthorizationProvider authProvider, Factory factory,
- InetSocketAddress socketAddress, StatusRecorder recorder) {
+ NetconfCallHomeServer(final SshClient sshClient, final CallHomeAuthorizationProvider authProvider,
+ final Factory factory, final InetSocketAddress socketAddress, final StatusRecorder recorder) {
this.client = Preconditions.checkNotNull(sshClient);
this.authProvider = Preconditions.checkNotNull(authProvider);
this.sessionFactory = Preconditions.checkNotNull(factory);
this.recorder = recorder;
sshClient.setServerKeyVerifier(this);
+ sshClient.addSessionListener(createSessionListener());
- SessionFactory clientSessions = new SessionFactory();
- clientSessions.setClient(sshClient);
- clientSessions.addListener(createSessionListener());
-
- IoServiceFactory minaFactory = createServiceFactory(sshClient);
- this.acceptor = minaFactory.createAcceptor(clientSessions);
+ this.acceptor = createServiceFactory(sshClient).createAcceptor(new SessionFactory(sshClient));
}
- private IoServiceFactory createServiceFactory(SshClient sshClient) {
+ private IoServiceFactory createServiceFactory(final SshClient sshClient) {
try {
return createMinaServiceFactory(sshClient);
} catch (NoClassDefFoundError e) {
LOG.warn("Mina is not available, defaulting to NIO.");
- return new Nio2ServiceFactory(sshClient);
+ return new Nio2ServiceFactory(sshClient, sshClient.getScheduledExecutorService(), false);
}
}
- protected IoServiceFactory createMinaServiceFactory(SshClient sshClient) {
- return new MinaServiceFactory(sshClient);
+ protected IoServiceFactory createMinaServiceFactory(final SshClient sshClient) {
+ return new MinaServiceFactory(sshClient, sshClient.getScheduledExecutorService(), false);
}
SessionListener createSessionListener() {
return new SessionListener() {
@Override
- public void sessionEvent(Session session, Event event) {
+ public void sessionEvent(final Session session, final Event event) {
ClientSession clientSession = (ClientSession) session;
LOG.debug("SSH session {} event {}", session, event);
switch (event) {
}
@Override
- public void sessionCreated(Session session) {
+ public void sessionCreated(final Session session) {
LOG.debug("SSH session {} created", session);
}
@Override
- public void sessionClosed(Session session) {
+ public void sessionClosed(final Session session) {
CallHomeSessionContext ctx = CallHomeSessionContext.getFrom((ClientSession) session);
if (ctx != null) {
ctx.removeSelf();
};
}
- private void doPostAuth(final ClientSession session) {
+ private static void doPostAuth(final ClientSession session) {
CallHomeSessionContext.getFrom(session).openNetconfChannel();
}
private SshFutureListener<AuthFuture> newAuthSshFutureListener(final ClientSession session) {
return new SshFutureListener<AuthFuture>() {
@Override
- public void operationComplete(AuthFuture authFuture) {
+ public void operationComplete(final AuthFuture authFuture) {
if (authFuture.isSuccess()) {
onSuccess();
} else if (authFuture.isFailure()) {
LOG.debug("Authorize success");
}
- private void onFailure(Throwable throwable) {
+ private void onFailure(final Throwable throwable) {
ClientSessionImpl impl = (ClientSessionImpl) session;
LOG.error("Authorize failed for session {}", session, throwable);
}
@Override
- public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) {
+ public boolean verifyServerKey(final ClientSession sshClientSession, final SocketAddress remoteAddress,
+ final PublicKey serverKey) {
final CallHomeAuthorization authorization = authProvider.provideAuth(remoteAddress, serverKey);
// server is not authorized
if (!authorization.isServerAllowed()) {
import io.netty.util.HashedWheelTimer;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
-import org.apache.sshd.SshClient;
+import org.apache.sshd.client.SshClient;
import org.opendaylight.netconf.callhome.protocol.CallHomeSessionContext.Factory;
import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory;
import org.opendaylight.yangtools.concepts.Builder;
private final CallHomeNetconfSubsystemListener subsystemListener;
private final StatusRecorder recorder;
- public NetconfCallHomeServerBuilder(CallHomeAuthorizationProvider authProvider,
- CallHomeNetconfSubsystemListener subsystemListener, StatusRecorder recorder) {
+ public NetconfCallHomeServerBuilder(final CallHomeAuthorizationProvider authProvider,
+ final CallHomeNetconfSubsystemListener subsystemListener, final StatusRecorder recorder) {
this.authProvider = authProvider;
this.subsystemListener = subsystemListener;
this.recorder = recorder;
return sshClient;
}
- public void setSshClient(SshClient sshClient) {
+ public void setSshClient(final SshClient sshClient) {
this.sshClient = sshClient;
}
return nettyGroup;
}
- public void setNettyGroup(EventLoopGroup nettyGroup) {
+ public void setNettyGroup(final EventLoopGroup nettyGroup) {
this.nettyGroup = nettyGroup;
}
return negotiationFactory;
}
- public void setNegotiationFactory(NetconfClientSessionNegotiatorFactory negotiationFactory) {
+ public void setNegotiationFactory(final NetconfClientSessionNegotiatorFactory negotiationFactory) {
this.negotiationFactory = negotiationFactory;
}
return bindAddress;
}
- public void setBindAddress(InetSocketAddress bindAddress) {
+ public void setBindAddress(final InetSocketAddress bindAddress) {
this.bindAddress = bindAddress;
}
return sshClient != null ? sshClient : defaultSshClient();
}
- private SshClient defaultSshClient() {
+ private static SshClient defaultSshClient() {
return SshClient.setUpDefaultClient();
}
- private NetconfClientSessionNegotiatorFactory defaultNegotiationFactory() {
+ private static NetconfClientSessionNegotiatorFactory defaultNegotiationFactory() {
return new NetconfClientSessionNegotiatorFactory(new HashedWheelTimer(),
Optional.absent(), DEFAULT_SESSION_TIMEOUT_MILLIS);
}
- private EventLoopGroup defaultNettyGroup() {
+ private static EventLoopGroup defaultNettyGroup() {
return new LocalEventLoopGroup();
}
- private InetSocketAddress defaultBindAddress() {
+ private static InetSocketAddress defaultBindAddress() {
return new InetSocketAddress(DEFAULT_CALL_HOME_PORT);
}
}
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.PublicKey;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientChannel.Streaming;
-import org.apache.sshd.ClientSession;
import org.apache.sshd.client.channel.ChannelSubsystem;
+import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannel.Streaming;
import org.apache.sshd.client.future.OpenFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
-import org.apache.sshd.common.KeyExchange;
-import org.apache.sshd.common.Session.AttributeKey;
+import org.apache.sshd.common.AttributeStore.AttributeKey;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoInputStream;
import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.common.io.IoReadFuture;
import org.apache.sshd.common.io.IoSession;
-import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.kex.KeyExchange;
+import org.apache.sshd.common.util.buffer.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public void creatingAChannelSuccessfullyShouldResultInAnAttachedListener() throws IOException {
// given
OpenFuture mockFuture = mock(OpenFuture.class);
- ChannelSubsystem mockChannel = mock(ChannelSubsystem.class);
- Mockito.doReturn(mockFuture).when(mockChannel).open();
- Mockito.doReturn(mockChannel).when(mockSession).createSubsystemChannel(anyString());
+ ChannelSubsystem mockChannelSubsystem = mock(ChannelSubsystem.class);
+ Mockito.doReturn(mockFuture).when(mockChannelSubsystem).open();
+ Mockito.doReturn(mockChannelSubsystem).when(mockSession).createSubsystemChannel(anyString());
Mockito.doReturn(null).when(mockFuture).addListener(any(SshFutureListener.class));
- doNothing().when(mockChannel).setStreaming(any(Streaming.class));
+ doNothing().when(mockChannelSubsystem).setStreaming(any(Streaming.class));
instance = realFactory.createIfNotExists(mockSession, mockAuth, address);
// when
instance.openNetconfChannel();
static class TestableContext extends CallHomeSessionContext {
MinaSshNettyChannel minaMock;
- TestableContext(ClientSession sshSession, CallHomeAuthorization authorization,
- InetSocketAddress address, CallHomeSessionContext.Factory factory,
- MinaSshNettyChannel minaMock) {
+ TestableContext(final ClientSession sshSession, final CallHomeAuthorization authorization,
+ final InetSocketAddress address, final CallHomeSessionContext.Factory factory,
+ final MinaSshNettyChannel minaMock) {
super(sshSession, authorization, address, factory);
this.minaMock = minaMock;
}
@Override
- protected MinaSshNettyChannel newMinaSshNettyChannel(ClientChannel netconfChannel) {
+ protected MinaSshNettyChannel newMinaSshNettyChannel(final ClientChannel netconfChannel) {
return minaMock;
}
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.io.IoInputStream;
import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.common.io.IoReadFuture;
import org.apache.sshd.common.io.IoWriteFuture;
-import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.util.buffer.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
-import org.apache.sshd.ClientSession;
-import org.apache.sshd.SshClient;
+import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionImpl;
-import org.apache.sshd.common.Session;
-import org.apache.sshd.common.SessionListener;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoHandler;
import org.apache.sshd.common.io.IoServiceFactory;
+import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.session.SessionListener;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
Mockito.doReturn("testAddr").when(mockSocketAddr).toString();
PublicKey mockPublicKey = mock(PublicKey.class);
- CallHomeAuthorization mockAuth = mock(CallHomeAuthorization.class);
Mockito.doReturn("test").when(mockAuth).toString();
Mockito.doReturn(true).when(mockAuth).isServerAllowed();
Mockito.doReturn("some-session-name").when(mockAuth).getSessionName();
static class TestableCallHomeServer extends NetconfCallHomeServer {
static IoServiceFactory minaServiceFactory;
- static SshClient factoryHook(SshClient client, IoServiceFactory minaFactory) {
+ static SshClient factoryHook(final SshClient client, final IoServiceFactory minaFactory) {
minaServiceFactory = minaFactory;
return client;
}
SshClient client;
- TestableCallHomeServer(SshClient sshClient, CallHomeAuthorizationProvider authProvider,
- CallHomeSessionContext.Factory factory, InetSocketAddress socketAddress,
- IoServiceFactory minaFactory, StatusRecorder recorder) {
+ TestableCallHomeServer(final SshClient sshClient, final CallHomeAuthorizationProvider authProvider,
+ final CallHomeSessionContext.Factory factory, final InetSocketAddress socketAddress,
+ final IoServiceFactory minaFactory, final StatusRecorder recorder) {
super(factoryHook(sshClient, minaFactory), authProvider, factory, socketAddress, recorder);
client = sshClient;
}
@Override
- protected IoServiceFactory createMinaServiceFactory(SshClient sshClient) {
+ protected IoServiceFactory createMinaServiceFactory(final SshClient sshClient) {
return minaServiceFactory;
}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
+import java.security.GeneralSecurityException;
import java.security.PublicKey;
-import java.security.spec.InvalidKeySpecException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
private final CallhomeStatusReporter statusReporter;
- CallHomeAuthProviderImpl(DataBroker broker) {
+ CallHomeAuthProviderImpl(final DataBroker broker) {
configReg = broker.registerDataTreeChangeListener(GLOBAL, globalConfig);
deviceReg = broker.registerDataTreeChangeListener(ALLOWED_DEVICES, deviceConfig);
deviceOpReg = broker.registerDataTreeChangeListener(ALLOWED_OP_DEVICES, deviceOp);
@Nonnull
@Override
- public CallHomeAuthorization provideAuth(@Nonnull SocketAddress remoteAddress, @Nonnull PublicKey serverKey) {
+ public CallHomeAuthorization provideAuth(@Nonnull final SocketAddress remoteAddress,
+ @Nonnull final PublicKey serverKey) {
Device deviceSpecific = deviceConfig.get(serverKey);
String sessionName;
Credentials deviceCred;
deviceOpReg.close();
}
- private String fromRemoteAddress(SocketAddress remoteAddress) {
+ private static String fromRemoteAddress(final SocketAddress remoteAddress) {
if (remoteAddress instanceof InetSocketAddress) {
InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
return InetAddresses.toAddrString(socketAddress.getAddress()) + ":" + socketAddress.getPort();
private final ConcurrentMap<PublicKey, Device> byPublicKey = new ConcurrentHashMap<>();
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Device>> mods) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Device>> mods) {
for (DataTreeModification<Device> dataTreeModification : mods) {
DataObjectModification<Device> rootNode = dataTreeModification.getRootNode();
process(rootNode);
}
}
- private void process(DataObjectModification<Device> deviceMod) {
+ private void process(final DataObjectModification<Device> deviceMod) {
Device before = deviceMod.getDataBefore();
Device after = deviceMod.getDataAfter();
}
}
- private void putDevice(Device device) {
+ private void putDevice(final Device device) {
PublicKey key = publicKey(device);
if (key == null) {
return;
byPublicKey.put(key, device);
}
- private void removeDevice(Device device) {
+ private void removeDevice(final Device device) {
PublicKey key = publicKey(device);
if (key == null) {
return;
byPublicKey.remove(key);
}
- private PublicKey publicKey(Device device) {
+ private PublicKey publicKey(final Device device) {
String hostKey = device.getSshHostKey();
try {
return keyDecoder.decodePublicKey(hostKey);
- } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
+ } catch (GeneralSecurityException e) {
LOG.error("Unable to decode SSH key for {}. Ignoring update for this device", device.getUniqueId(), e);
return null;
}
}
- private Device get(PublicKey key) {
+ private Device get(final PublicKey key) {
return byPublicKey.get(key);
}
}
private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Device>> mods) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Device>> mods) {
for (DataTreeModification<Device> dataTreeModification : mods) {
DataObjectModification<Device> rootNode = dataTreeModification.getRootNode();
process(rootNode);
}
}
- private void process(DataObjectModification<Device> deviceMod) {
+ private void process(final DataObjectModification<Device> deviceMod) {
Device before = deviceMod.getDataBefore();
Device after = deviceMod.getDataAfter();
}
}
- private void putDevice(Device device) {
+ private void putDevice(final Device device) {
String key = device.getSshHostKey();
byPublicKey.put(key, device);
}
- private void removeDevice(Device device) {
+ private void removeDevice(final Device device) {
String key = device.getSshHostKey();
byPublicKey.remove(key);
}
- Device get(PublicKey serverKey) {
+ Device get(final PublicKey serverKey) {
String skey = "";
try {
private volatile Global current = null;
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Global>> mods) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Global>> mods) {
for (DataTreeModification<Global> dataTreeModification : mods) {
current = dataTreeModification.getRootNode().getDataAfter();
}
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
+import java.security.GeneralSecurityException;
import java.security.PublicKey;
-import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
private final DataBroker dataBroker;
private final ListenerRegistration<CallhomeStatusReporter> reg;
- CallhomeStatusReporter(DataBroker broker) {
+ CallhomeStatusReporter(final DataBroker broker) {
this.dataBroker = broker;
this.reg = dataBroker.registerDataTreeChangeListener(new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
NETCONF_TOPO_IID.child(Node.class)), this);
}
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Node>> changes) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Node>> changes) {
for (DataTreeModification<Node> change: changes) {
final DataObjectModification<Node> rootNode = change.getRootNode();
final InstanceIdentifier<Node> identifier = change.getRootPath().getRootIdentifier();
}
}
- private boolean isNetconfNode(Node node) {
+ private static boolean isNetconfNode(final Node node) {
return node.getAugmentation(NetconfNode.class) != null;
}
- private NodeId getNodeId(final InstanceIdentifier<?> path) {
+ private static NodeId getNodeId(final InstanceIdentifier<?> path) {
NodeKey key = path.firstKeyOf(Node.class);
return key != null ? key.getNodeId() : null;
}
- private void handledNetconfNode(NodeId nodeId, NetconfNode nnode) {
+ private void handledNetconfNode(final NodeId nodeId, final NetconfNode nnode) {
NetconfNodeConnectionStatus.ConnectionStatus csts = nnode.getConnectionStatus();
switch (csts) {
}
}
- private void handleConnectedNetconfNode(NodeId nodeId) {
+ private void handleConnectedNetconfNode(final NodeId nodeId) {
// Fully connected, all services for remote device are
// available from the MountPointService.
LOG.debug("NETCONF Node: {} is fully connected", nodeId.getValue());
}
}
- private void handleDisconnectedNetconfNode(NodeId nodeId) {
+ private void handleDisconnectedNetconfNode(final NodeId nodeId) {
LOG.debug("NETCONF Node: {} disconnected", nodeId.getValue());
Device opDev = readAndGetDevice(nodeId);
}
}
- private void handleUnableToConnectNetconfNode(NodeId nodeId) {
+ private void handleUnableToConnectNetconfNode(final NodeId nodeId) {
// The maximum configured number of reconnect attempts
// have been reached. No more reconnects will be
// attempted by the Netconf Connector.
}
}
- void asForceListedDevice(String id, PublicKey serverKey) {
+ void asForceListedDevice(final String id, final PublicKey serverKey) {
NodeId nid = new NodeId(id);
Device device = newDevice(id, serverKey, Device1.DeviceStatus.DISCONNECTED);
writeDevice(nid, device);
}
- void asUnlistedDevice(String id, PublicKey serverKey) {
+ void asUnlistedDevice(final String id, final PublicKey serverKey) {
NodeId nid = new NodeId(id);
Device device = newDevice(id, serverKey, Device1.DeviceStatus.FAILEDNOTALLOWED);
writeDevice(nid, device);
}
- private Device newDevice(String id, PublicKey serverKey, Device1.DeviceStatus status) {
+ private static Device newDevice(final String id, final PublicKey serverKey, final Device1.DeviceStatus status) {
String sshEncodedKey = serverKey.toString();
try {
sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
return builder.build();
}
- private Device readAndGetDevice(NodeId nodeId) {
+ private Device readAndGetDevice(final NodeId nodeId) {
return readDevice(nodeId).orNull();
}
@Nonnull
- private Optional<Device> readDevice(NodeId nodeId) {
+ private Optional<Device> readDevice(final NodeId nodeId) {
ReadOnlyTransaction opTx = dataBroker.newReadOnlyTransaction();
InstanceIdentifier<Device> deviceIID = buildDeviceInstanceIdentifier(nodeId);
}
}
- private void writeDevice(NodeId nodeId, Device modifiedDevice) {
+ private void writeDevice(final NodeId nodeId, final Device modifiedDevice) {
ReadWriteTransaction opTx = dataBroker.newReadWriteTransaction();
opTx.merge(LogicalDatastoreType.OPERATIONAL, buildDeviceInstanceIdentifier(nodeId), modifiedDevice);
opTx.submit();
}
- private InstanceIdentifier<Device> buildDeviceInstanceIdentifier(NodeId nodeId) {
+ private static InstanceIdentifier<Device> buildDeviceInstanceIdentifier(final NodeId nodeId) {
return InstanceIdentifier.create(NetconfCallhomeServer.class)
.child(AllowedDevices.class)
.child(Device.class, new DeviceKey(nodeId.getValue()));
}
- private Device withConnectedStatus(Device opDev) {
+ private static Device withConnectedStatus(final Device opDev) {
Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.CONNECTED).build();
return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId())
.setSshHostKey(opDev.getSshHostKey()).build();
}
- private Device withFailedStatus(Device opDev) {
+ private static Device withFailedStatus(final Device opDev) {
Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILED).build();
return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId())
.setSshHostKey(opDev.getSshHostKey()).build();
}
- private Device withDisconnectedStatus(Device opDev) {
+ private static Device withDisconnectedStatus(final Device opDev) {
Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build();
return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId())
.setSshHostKey(opDev.getSshHostKey()).build();
}
- private Device withFailedAuthStatus(Device opDev) {
+ private static Device withFailedAuthStatus(final Device opDev) {
Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILEDAUTHFAILURE).build();
return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId())
.setSshHostKey(opDev.getSshHostKey()).build();
}
- private void setDeviceStatus(Device device) {
+ private void setDeviceStatus(final Device device) {
WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
InstanceIdentifier<Device> deviceIId =
InstanceIdentifier.create(NetconfCallhomeServer.class)
}
@Override
- public void reportFailedAuth(PublicKey sshKey) {
+ public void reportFailedAuth(final PublicKey sshKey) {
AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder();
for (Device device : getDevicesAsList()) {
setDeviceStatus(failedDevice);
return;
}
- } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) {
+ } catch (GeneralSecurityException e) {
LOG.error("Failed decoding a device key with host key: {} {}", keyString, e);
return;
}
public class Configuration {
public abstract static class ConfigurationException extends RuntimeException {
- ConfigurationException(String msg) {
+ ConfigurationException(final String msg) {
super(msg);
}
- ConfigurationException(String msg, Exception cause) {
+ ConfigurationException(final String msg, final Exception cause) {
super(msg, cause);
}
}
public static class ReadException extends ConfigurationException {
- ReadException(String msg, Exception exc) {
+ ReadException(final String msg, final Exception exc) {
super(msg, exc);
}
}
public static class MissingException extends ConfigurationException {
private final String key;
- MissingException(String key) {
+ MissingException(final String key) {
super("Key not found: " + key);
this.key = key;
}
private final String key;
private final String value;
- IllegalValueException(String key, String value) {
+ IllegalValueException(final String key, final String value) {
super("Key has an illegal value. Key: " + key + ", Value: " + value);
this.key = key;
this.value = value;
}
+ IllegalValueException(final String key, final String value, final Exception cause) {
+ super("Key has an illegal value. Key: " + key + ", Value: " + value, cause);
+ this.key = key;
+ this.value = value;
+ }
+
public String getKey() {
return key;
}
properties = new Properties();
}
- public Configuration(String path) throws ConfigurationException {
+ public Configuration(final String path) throws ConfigurationException {
this.path = path;
try {
this.properties = readFromPath(path);
}
}
- private Properties readFromPath(String path) throws IOException {
- return readFromFile(new File(path));
+ private Properties readFromPath(final String filePath) throws IOException {
+ return readFromFile(new File(filePath));
}
- private Properties readFromFile(File file) throws IOException {
+ private Properties readFromFile(final File file) throws IOException {
FileInputStream stream = new FileInputStream(file);
properties = readFrom(stream);
return properties;
}
- private Properties readFrom(InputStream stream) throws IOException {
+ private static Properties readFrom(final InputStream stream) throws IOException {
Properties properties = new Properties();
properties.load(stream);
return properties;
}
- public void set(String key, String value) {
+ public void set(final String key, final String value) {
properties.setProperty(key, value);
}
- String get(String key) {
+ String get(final String key) {
String result = (String) properties.get(key);
if (result == null) {
throw new MissingException(key);
return result;
}
- public int getAsPort(String key) {
+ public int getAsPort(final String key) {
String keyValue = get(key);
try {
int newPort = Integer.parseInt(keyValue);
}
return newPort;
} catch (NumberFormatException e) {
- throw new IllegalValueException(key, keyValue);
+ throw new IllegalValueException(key, keyValue, e);
}
}
}
private int port = 0; // 0 = use default in NetconfCallHomeBuilder
private final CallhomeStatusReporter statusReporter;
- public IetfZeroTouchCallHomeServerProvider(DataBroker dataBroker, CallHomeMountDispatcher mountDispacher) {
+ public IetfZeroTouchCallHomeServerProvider(final DataBroker dataBroker,
+ final CallHomeMountDispatcher mountDispacher) {
this.dataBroker = dataBroker;
this.mountDispacher = mountDispacher;
this.authProvider = new CallHomeAuthProviderImpl(dataBroker);
}
}
- public void setPort(String portStr) {
+ public void setPort(final String portStr) {
try {
Configuration configuration = new Configuration();
configuration.set(CALL_HOME_PORT_KEY, portStr);
}
@VisibleForTesting
- void assertValid(Object obj, String description) {
+ void assertValid(final Object obj, final String description) {
if (obj == null) {
throw new RuntimeException(
String.format("Failed to find %s in IetfZeroTouchCallHomeProvider.initialize()", description));
}
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<AllowedDevices>> changes) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<AllowedDevices>> changes) {
// In case of any changes to the devices datatree, register the changed values with callhome server
// As of now, no way to add a new callhome client key to the CallHomeAuthorization instance since
// its created under CallHomeAuthorizationProvider.
}
}
- private void handleDeletedDevices(Set<InstanceIdentifier<?>> deletedDevices) {
+ private void handleDeletedDevices(final Set<InstanceIdentifier<?>> deletedDevices) {
if (deletedDevices.isEmpty()) {
return;
}
}
}
- private List<Device> getReadDevices(
- ListenableFuture<Optional<AllowedDevices>> devicesFuture) throws InterruptedException, ExecutionException {
+ private static List<Device> getReadDevices(final ListenableFuture<Optional<AllowedDevices>> devicesFuture)
+ throws InterruptedException, ExecutionException {
Optional<AllowedDevices> opt = devicesFuture.get();
return opt.isPresent() ? opt.get().getDevice() : Collections.emptyList();
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.netty.channel.Channel;
import java.io.IOException;
-import java.io.InputStream;
import java.math.BigInteger;
import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceListener;
final BindingRuntimeContext ret = super.getBindingRuntimeContext();
doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
- final List<InputStream> streams = getYangs();
- try {
- doReturn(YangParserTestUtils.parseYangStreams(streams)).when(ret).getSchemaContext();
- } catch (final ReactorException e) {
- throw new RuntimeException("Unable to build schema context from " + streams, e);
- }
+ doReturn(getSchemaContext()).when(ret).getSchemaContext();
return ret;
}
}
}
- private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
- final List<InputStream> yangDependencies = getYangs();
-
- final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
+ private static Map<String, Map<String, ModuleMXBeanEntry>> getMbes() {
- final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(yangDependencies);
- final YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
- @Override
- public SchemaContext getSchemaContext() {
- return schemaContext;
- }
- }, mock(SchemaSourceProvider.class));
+ final SchemaContext schemaContext = getSchemaContext();
+ final YangStoreService yangStoreService = new YangStoreService(() -> schemaContext,
+ mock(SchemaSourceProvider.class));
final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
doReturn(schemaContext).when(bindingRuntimeContext).getSchemaContext();
doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
yangStoreService.refresh(bindingRuntimeContext);
+ final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = new HashMap<>();
mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
return mBeanEntries;
return enumBiMap;
}
- private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
- final SchemaContext resolveSchemaContext = YangParserTestUtils.parseYangStreams(getYangs());
- return resolveSchemaContext.getModules();
+ private static Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() {
+ return getSchemaContext().getModules();
}
@Test
return response;
}
- private List<InputStream> getYangs() {
- 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<>();
- for (final String path : paths) {
- final InputStream is = Preconditions
- .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
- yangDependencies.add(is);
- }
- return Lists.newArrayList(yangDependencies);
+ private static SchemaContext getSchemaContext() {
+ return YangParserTestUtils.parseYangResources(NetconfMappingTest.class,
+ "/META-INF/yang/config@2013-04-05.yang", "/META-INF/yang/rpc-context@2013-06-17.yang",
+ "/META-INF/yang/config-test@2013-06-13.yang", "/META-INF/yang/config-test-impl@2013-04-03.yang",
+ "/META-INF/yang/test-types@2013-11-27.yang", "/META-INF/yang/test-groups@2014-12-08.yang",
+ "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
}
private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction,
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
package org.opendaylight.netconf.mdsal.connector;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
+import java.util.Optional;
import java.util.Set;
+import java.util.concurrent.ExecutionException;
import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.config.util.capability.YangModuleCapability;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactoryListener;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-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;
final Module module, final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency) {
final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(),
- SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() :
- Optional.of(module.getQNameModule().getFormattedRevision()));
+ module.getRevision());
InputStream sourceStream = null;
String source;
try {
- sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).checkedGet()
- .openStream();
+ sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).get().openStream();
source = CharStreams.toString(new InputStreamReader(sourceStream, StandardCharsets.UTF_8));
- } catch (IOException | SchemaSourceException e) {
+ } catch (ExecutionException | InterruptedException | IOException e) {
LOG.warn("Ignoring source for module {}. Unable to read content", moduleSourceIdentifier, e);
source = null;
}
LOG.warn("Missing source for module {}. This module will not be available from netconf server",
moduleSourceIdentifier);
- return Optional.absent();
+ return Optional.empty();
}
@Override
LOG.debug("Transaction {} failed on", candidateTransaction, e);
final String cause = e.getCause() != null ? (" Cause: " + e.getCause().getMessage()) : "";
throw new DocumentedException(
- "Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause,
+ "Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause, e,
ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
} finally {
allOpenReadWriteTransactions.remove(candidateTransaction);
import com.google.common.collect.ImmutableMap;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
import org.opendaylight.netconf.api.NetconfDocumentedException;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
case CREATE:
try {
final Optional<NormalizedNode<?, ?>> readResult =
- rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
+ rwtx.read(LogicalDatastoreType.CONFIGURATION, path).get();
if (readResult.isPresent()) {
throw new DocumentedException("Data already exists, cannot execute CREATE operation",
ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
}
mergeParentMixin(rwtx, path, changeData);
rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
- } catch (final ReadFailedException e) {
+ } catch (final InterruptedException | ExecutionException e) {
LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
}
break;
case DELETE:
try {
final Optional<NormalizedNode<?, ?>> readResult =
- rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
+ rwtx.read(LogicalDatastoreType.CONFIGURATION, path).get();
if (!readResult.isPresent()) {
throw new DocumentedException("Data is missing, cannot execute DELETE operation",
ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
}
rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
- } catch (final ReadFailedException e) {
+ } catch (final InterruptedException | ExecutionException e) {
LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
}
break;
}
private void mergeParentMixin(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
- final NormalizedNode change) {
+ final NormalizedNode<?, ?> change) {
final YangInstanceIdentifier parentNodeYid = path.getParent();
if (change instanceof MapEntryNode) {
final SchemaNode schemaNode = SchemaContextUtil.findNodeInSchemaContext(
private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element)
throws DocumentedException {
- Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
+ final Iterator<Module> it;
try {
// returns module with newest revision since findModuleByNamespace returns a set of modules and we only
// need the newest one
- final Module module =
- schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
- if (module == null) {
- // no module is present with this namespace
- throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
- ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
- }
- final DataSchemaNode schemaNode =
- module.getDataChildByName(QName.create(module.getQNameModule(), element.getName()));
+ it = schemaContext.getCurrentContext().findModules(new URI(namespace)).iterator();
+ } catch (final URISyntaxException e) {
+ LOG.debug("Unable to create URI for namespace : {}", namespace);
+ return Optional.absent();
+ }
+
+ if (!it.hasNext()) {
+ // no module is present with this namespace
+ throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
+ ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
+ }
+
+ final Module module = it.next();
+ final java.util.Optional<DataSchemaNode> schemaNode =
+ module.findDataChildByName(QName.create(module.getQNameModule(), element.getName()));
+ if (!schemaNode.isPresent()) {
if (schemaNode != null) {
- dataSchemaNode = Optional.of(schemaNode);
- } else {
throw new DocumentedException(
- "Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
- ErrorType.APPLICATION,
- ErrorTag.UNKNOWN_NAMESPACE,
- ErrorSeverity.ERROR);
+ "Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
+ ErrorType.APPLICATION,
+ ErrorTag.UNKNOWN_NAMESPACE,
+ ErrorSeverity.ERROR);
}
- } catch (final URISyntaxException e) {
- LOG.debug("Unable to create URI for namespace : {}", namespace);
}
- return dataSchemaNode;
+ return Optional.fromJavaUtil(schemaNode);
}
private static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
final class EditOperationNormalizedNodeStreamWriter extends ImmutableNormalizedNodeStreamWriter
implements NormalizedNodeStreamAttributeWriter {
- private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(), null,
+ private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(),
XmlNetconfConstants.OPERATION_ATTR_KEY);
private final DataTreeChangeTracker dataTreeChangeTracker;
package org.opendaylight.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import com.google.common.base.Throwables;
import com.google.common.util.concurrent.CheckedFuture;
import java.io.IOException;
import java.net.URI;
//this returns module with the newest revision if more then 1 module with same namespace is found
private Optional<Module> getModule(final URI namespaceURI) {
- return Optional.fromNullable(
- schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
+ return Optional.fromJavaUtil(schemaContext.getCurrentContext().findModule(namespaceURI));
}
private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
netconfOperationNamespace = operationElement.getNamespace();
} catch (final DocumentedException e) {
LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
- throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
+ throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
}
nnWriter.flush();
xmlWriter.flush();
} catch (XMLStreamException | IOException e) {
- Throwables.propagate(e);
+ throw new RuntimeException(e);
}
}
try {
validateInputRpc(xml, operationName);
} catch (final DocumentedException e) {
- throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(),
+ throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e, e.getErrorType(), e.getErrorTag(),
e.getErrorSeverity(), e.getErrorInfo());
}
try {
sourceDatastore = parseSource(xml);
} catch (final DocumentedException e) {
- throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(),
- e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e,
+ e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
return new GetConfigExecution(sourceDatastore);
import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
try {
final URI namespace = new URI(filterContent.getNamespace());
- final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
+ final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
final FilterTree filterTree = validateNode(
filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
} catch (final URISyntaxException e) {
- throw new RuntimeException("Wrong namespace in element + " + filterContent.toString());
+ throw new RuntimeException("Wrong namespace in element + " + filterContent.toString(), e);
} catch (final ValidationException e) {
LOG.debug("Filter content isn't valid", e);
- throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
+ throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
DocumentedException.ErrorSeverity.ERROR);
final DataSchemaNode childSchema = path.getLast();
validateNode(childElement, childSchema, subtree);
} catch (URISyntaxException | MissingNameSpaceException e) {
- throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
+ throw new RuntimeException("Wrong namespace in element + " + childElement.toString(), e);
}
}
return tree;
}
FilterTree addChild(final DataSchemaNode data) {
- final Type type;
- if (data instanceof ChoiceCaseNode) {
- type = Type.CHOICE_CASE;
+ final Type childType;
+ if (data instanceof CaseSchemaNode) {
+ childType = Type.CHOICE_CASE;
} else if (data instanceof ListSchemaNode) {
- type = Type.LIST;
+ childType = Type.LIST;
} else {
- type = Type.OTHER;
+ childType = Type.OTHER;
}
- final QName name = data.getQName();
- FilterTree childTree = children.get(name);
+ final QName childName = data.getQName();
+ FilterTree childTree = children.get(childName);
if (childTree == null) {
- childTree = new FilterTree(name, type, data);
+ childTree = new FilterTree(childName, childType, data);
}
- children.put(name, childTree);
+ children.put(childName, childTree);
return childTree;
}
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.Futures;
-import java.io.InputStream;
import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.EnumMap;
-import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
- this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
+ this.schemaContext = YangParserTestUtils.parseYangResources(NetconfMDSalMappingTest.class,
+ "/META-INF/yang/config@2013-04-05.yang", "/yang/mdsal-netconf-mapping-test.yang");
schemaContext.getModules();
final SchemaService schemaService = createSchemaService();
datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
- 16, 16, "CommitFutures");
+ 16, 16, "CommitFutures", NetconfMDSalMappingTest.class);
final ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
this.transactionProvider = new TransactionProvider(cdb, SESSION_ID_FOR_REPORTING);
final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
final YangTextSchemaSource yangTextSchemaSource =
YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
- return Futures.immediateCheckedFuture(yangTextSchemaSource);
+ return Futures.immediateFuture(yangTextSchemaSource);
}).when(sourceProvider).getSource(any(SourceIdentifier.class));
+ " </edit-config>\n"
+ "</rpc>";
XmlElement xe = getXmlElement(stringWithoutPrefix);
- NodeList nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY);
+ NodeList nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY);
Assert.assertEquals(1, nodeList.getLength());
String stringWithPrefix =
+ "</nc:rpc>";
xe = getXmlElement(stringWithPrefix);
- nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY);
+ nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY);
Assert.assertEquals(1, nodeList.getLength());
String stringWithoutTarget =
xe = getXmlElement(stringWithoutTarget);
try {
- nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY);
+ nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY);
XmlElement.fromDomElement((Element) nodeList.item(0)).getOnlyChildElement();
Assert.fail("Not specified target, we should fail");
} catch (DocumentedException documentedException) {
}
- private XmlElement getXmlElement(final String elementAsString) throws Exception {
+ private static XmlElement getXmlElement(final String elementAsString) throws Exception {
Document document = XmlUtil.readXmlToDocument(elementAsString);
Element element = document.getDocumentElement();
return XmlElement.fromDomElement(element);
return response;
}
- private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config@2013-04-05.yang",
- "/yang/mdsal-netconf-mapping-test.yang");
- final List<InputStream> schemas = new ArrayList<>();
-
- for (final String schemaPath : schemaPaths) {
- final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
- schemas.add(resourceAsStream);
- }
-
- return schemas;
- }
-
private SchemaService createSchemaService() {
return new SchemaService() {
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
-import java.io.InputStream;
import java.net.URI;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.custommonkey.xmlunit.DetailedDiff;
return doc;
}
- private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
+ private static final DOMRpcService RPC_SERVICE_VOID_INVOKER = new DOMRpcService() {
@Nonnull
@Override
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
}
};
- private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
+ private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() {
@Nonnull
@Override
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
}
};
- private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
+ private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() {
@Nonnull
@Override
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
final Collection<DataContainerChild<? extends PathArgument, ?>> children =
(Collection<DataContainerChild<? extends PathArgument, ?>>) input.getValue();
- final Module module = schemaContext.findModuleByNamespaceAndRevision(
- type.getLastComponent().getNamespace(), null);
+ final Module module = schemaContext.findModule(type.getLastComponent().getNamespace()).orElse(null);
final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
module, module.getNamespace(), type.getLastComponent().getLocalName());
final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
@Nonnull
@Override
public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
- @Nonnull final T listener) {
+ @Nonnull final T lsnr) {
return null;
}
};
}).when(sourceProvider).getSource(any(SourceIdentifier.class));
- this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
+ this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
}
@Test
public void testVoidOutputRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testSuccesfullNonVoidInvocation() throws Exception {
final RuntimeRpc rpc = new RuntimeRpc(
- SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testSuccesfullContainerInvocation() throws Exception {
final RuntimeRpc rpc = new RuntimeRpc(
- SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testFailedInvocation() throws Exception {
final RuntimeRpc rpc = new RuntimeRpc(
- SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceFailedInvocation);
+ SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testVoidInputOutputRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
final HandlingPriority priority = rpc.canHandle(rpcDocument);
@Test
public void testBadNamespaceInRpc() throws Exception {
- final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
+ final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
try {
return null;
}
-
- private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang");
- final List<InputStream> schemas = new ArrayList<>();
-
- for (final String schemaPath : schemaPaths) {
- final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
- schemas.add(resourceAsStream);
- }
-
- return schemas;
- }
-}
\ No newline at end of file
+}
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.opendaylight.controller.config.util.xml.XmlElement;
@Test
public void testValidateTypes() throws Exception {
- final List<InputStream> sources = new ArrayList<>();
- sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang"));
- sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang"));
- sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang"));
- final SchemaContext context = YangParserTestUtils.parseYangStreams(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(Bug8084.class,
+ "/yang/filter-validator-test-mod-0.yang", "/yang/filter-validator-test-augment.yang",
+ "/yang/mdsal-netconf-mapping-test.yang");
final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
doReturn(context).when(currentContext).getCurrentContext();
final FilterContentValidator validator = new FilterContentValidator(currentContext);
import static org.mockito.Mockito.mock;
import com.google.common.base.Preconditions;
-import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Before
public void setUp() throws Exception {
- final List<InputStream> sources = new ArrayList<>();
- sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang"));
- sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang"));
- sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang"));
- final SchemaContext context = YangParserTestUtils.parseYangStreams(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(FilterContentValidatorTest.class,
+ "/yang/filter-validator-test-mod-0.yang", "/yang/filter-validator-test-augment.yang",
+ "/yang/mdsal-netconf-mapping-test.yang");
+
final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
doReturn(context).when(currentContext).getCurrentContext();
validator = new FilterContentValidator(currentContext);
if (expected.startsWith("success")) {
final String expId = expected.replace("success=", "");
final YangInstanceIdentifier actual = validator.validate(filterContent);
- final YangInstanceIdentifier expected = fromString(expId);
- Assert.assertEquals(expected, actual);
+ Assert.assertEquals(fromString(expId), actual);
} else if (expected.startsWith("error")) {
try {
validator.validate(filterContent);
}
private static QName createNodeQName(final QName prev, final String input) {
- final QName qName = QName.create(input);
- if (qName.getModule().getNamespace() != null) {
- return qName;
+ try {
+ return QName.create(input);
+ } catch (IllegalArgumentException e) {
+ return QName.create(Preconditions.checkNotNull(prev), input);
}
-
- return QName.create(Preconditions.checkNotNull(prev), input);
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
// TODO Conformance type is always set to Implement value, but it should it really be like this?
// TODO Add also deviations and features lists to module entries
- moduleBuilder.setName(new YangIdentifier(module.getName()))
- .setRevision(new OptionalRevision(module.getQNameModule().getFormattedRevision()))
- .setNamespace(new Uri(module.getNamespace().toString()))
- .setConformanceType(ConformanceType.Implement)
- .setSubmodules(createSubmodulesForModule(module));
+ moduleBuilder.setName(new YangIdentifier(module.getName()));
+
+ module.getQNameModule().getRevision().ifPresent(rev -> moduleBuilder.setRevision(
+ new OptionalRevision(rev.toString())));
- return moduleBuilder.build();
+ return moduleBuilder.setNamespace(new Uri(module.getNamespace().toString()))
+ .setConformanceType(ConformanceType.Implement)
+ .setSubmodules(createSubmodulesForModule(module))
+ .build();
}
- private Submodules createSubmodulesForModule(final Module module) {
+ private static Submodules createSubmodulesForModule(final Module module) {
final List<Submodule> submodulesList = Lists.newArrayList();
for (final Module subModule : module.getSubmodules()) {
- final SubmoduleBuilder subModuleEntryBuilder = new SubmoduleBuilder();
- subModuleEntryBuilder.setName(new YangIdentifier(subModule.getName()))
- .setRevision(new OptionalRevision(subModule.getQNameModule().getFormattedRevision()));
+ final SubmoduleBuilder subModuleEntryBuilder = new SubmoduleBuilder()
+ .setName(new YangIdentifier(subModule.getName()));
+ subModule.getQNameModule().getRevision().ifPresent(
+ rev -> subModuleEntryBuilder.setRevision(new OptionalRevision(rev.toString())));
submodulesList.add(subModuleEntryBuilder.build());
}
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
-import java.io.InputStream;
-import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState()));
}
- private SchemaContext getSchema() throws Exception {
- final List<InputStream> modelsToParse = Lists.newArrayList(
- SchemaServiceToMdsalWriterTest.class.getResourceAsStream("/test-module.yang"),
- SchemaServiceToMdsalWriterTest.class.getResourceAsStream("/test-submodule.yang")
- );
- return YangParserTestUtils.parseYangStreams(modelsToParse);
+ private static SchemaContext getSchema() {
+ return YangParserTestUtils.parseYangResources(SchemaServiceToMdsalWriterTest.class, "/test-module.yang",
+ "/test-submodule.yang");
}
- private ModulesState createTestModuleState() {
+ private static ModulesState createTestModuleState() {
Submodule sub = new SubmoduleBuilder().setName(new YangIdentifier("test-submodule"))
- .setRevision(new OptionalRevision("1970-01-01"))
.build();
Module module = new ModuleBuilder().setName(new YangIdentifier("test-module"))
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
try {
domPublish.putNotification(new TopicDOMNotification(topicNotification));
} catch (final InterruptedException e) {
- throw Throwables.propagate(e);
+ throw new RuntimeException(e);
}
}
return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG).withValue(new DOMSource(element)).build();
} catch (IOException | XMLStreamException e) {
LOG.error("Unable to encapsulate notification.", e);
- throw Throwables.propagate(e);
+ throw new RuntimeException(e);
}
}
/**
* Helper class to keep connection status of netconf node and event source registration object.
*/
-public class NetconfEventSourceRegistration implements AutoCloseable {
+public final class NetconfEventSourceRegistration implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceRegistration.class);
private static final YangInstanceIdentifier NETCONF_DEVICE_DOM_PATH = YangInstanceIdentifier.builder()
private Date lastEventTime;
protected final ConcurrentHashMap<SchemaPath, Set<TopicId>> notificationTopicMap = new ConcurrentHashMap<>();
- protected NotificationTopicRegistration(NotificationSourceType notificationSourceType, String sourceName,
- String notificationUrnPrefix) {
+ protected NotificationTopicRegistration(final NotificationSourceType notificationSourceType,
+ final String sourceName, final String notificationUrnPrefix) {
this.notificationSourceType = notificationSourceType;
this.sourceName = sourceName;
this.notificationUrnPrefix = notificationUrnPrefix;
return active;
}
- protected void setActive(boolean active) {
+ protected void setActive(final boolean active) {
this.active = active;
}
* @param notificationPath path
* @return topicIds
*/
- Set<TopicId> getTopicsForNotification(SchemaPath notificationPath) {
+ Set<TopicId> getTopicsForNotification(final SchemaPath notificationPath) {
final Set<TopicId> topicIds = notificationTopicMap.get(notificationPath);
return topicIds != null ? topicIds : Sets.newHashSet();
}
* @param notificationPath path
* @return true, if notification belongs to registration namespace
*/
- boolean checkNotificationPath(SchemaPath notificationPath) {
+ boolean checkNotificationPath(final SchemaPath notificationPath) {
if (notificationPath == null) {
return false;
}
return Optional.fromNullable(lastEventTime);
}
- void setLastEventTime(Date lastEventTime) {
+ void setLastEventTime(final Date lastEventTime) {
this.lastEventTime = lastEventTime;
}
* Registers associated event source notification to topic.
*
* @param topicId topic id
- * @return true, if successful
*/
abstract void unRegisterNotificationTopic(TopicId topicId);
return replaySupported;
}
- protected void setReplaySupported(boolean replaySupported) {
+ protected void setReplaySupported(final boolean replaySupported) {
this.replaySupported = replaySupported;
}
final List<String> streamNames = Lists.transform(availableStreams, new Function<Stream, String>() {
@Nullable
@Override
- public String apply(@Nullable Stream input) {
+ public String apply(@Nullable final Stream input) {
return input.getName().getValue();
}
});
streamNames.contains(STREAM_2);
}
- private String getStreamName(ContainerNode value) {
+ private static String getStreamName(final ContainerNode value) {
YangInstanceIdentifier.NodeIdentifier stream =
new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "stream"));
return (String) value.getChild(stream).get().getValue();
}
- private Optional<?> getDate(ContainerNode value) {
+ private static Optional<?> getDate(final ContainerNode value) {
YangInstanceIdentifier.NodeIdentifier startTime =
new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "startTime"));
- return value.getChild(startTime);
+ return Optional.fromJavaUtil(value.getChild(startTime));
}
}
\ No newline at end of file
final Node nodeId1 = NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus
.Connected, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX);
doReturn(nodeId1).when(mount).getNode();
+ doReturn(nodeId1.getNodeId().getValue()).when(mount).getNodeId();
Map<String, String> streamMap = new HashMap<>();
streamMap.put(NOTIFICATION_1_PATH.getLastComponent().getNamespace().toString(), "stream-1");
final TopicDOMNotification value = (TopicDOMNotification) captor.getValue();
final QName qname = TopicNotification.QNAME;
final YangInstanceIdentifier.NodeIdentifier topicIdNode =
- new YangInstanceIdentifier.NodeIdentifier(QName.create(qname.getNamespace().toString(), qname
- .getFormattedRevision(), "topic-id"));
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(qname, "topic-id"));
final Object actualTopicId = value.getBody().getChild(topicIdNode).get().getValue();
Assert.assertEquals(topic1.getTopicId(), actualTopicId);
}
verify(domNotificationPublishServiceMock, only()).putNotification(any());
}
- private Stream createStream(String name) {
+ private static Stream createStream(final String name) {
return new StreamBuilder()
.setName(new StreamNameType(name))
.setReplaySupport(true)
.build();
}
- private NotificationDefinition getNotificationDefinitionMock(QName qualifiedName) {
+ private static NotificationDefinition getNotificationDefinitionMock(final QName qualifiedName) {
NotificationDefinition notification = mock(NotificationDefinition.class);
doReturn(qualifiedName).when(notification).getQName();
doReturn(SchemaPath.create(true, qualifiedName)).when(notification).getPath();
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
/**
* Class represents change in netconf session.
*/
-public class SessionEvent {
+public final class SessionEvent {
private final NetconfManagementSession session;
private final Type type;
public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
NETCONF_MONITORING, NETCONF_NOTIFICATION);
+
+ private NetconfConstants() {
+
+ }
}
@Test
public void testStaticConstructor() throws Exception {
- NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
- assertEquals(header.toString(), this.header.toString());
- assertEquals(header.toFormattedString(), this.header.toFormattedString());
+ NetconfHelloMessageAdditionalHeader hdr = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
+ assertEquals(hdr.toString(), this.header.toString());
+ assertEquals(hdr.toFormattedString(), this.header.toFormattedString());
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public final synchronized void onSessionUp(NetconfClientSession clientSession) {
this.clientSession = Preconditions.checkNotNull(clientSession);
LOG.debug("Client session {} went up", clientSession);
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public final void onSessionDown(NetconfClientSession clientSession, Exception exception) {
LOG.debug("Client Session {} went down unexpectedly", clientSession, exception);
tearDown(exception);
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public final void onSessionTerminated(NetconfClientSession clientSession,
NetconfTerminationReason netconfTerminationReason) {
LOG.debug("Client Session {} terminated, reason: {}", clientSession,
return new NetconfClientConfigurationBuilder();
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withAddress(final InetSocketAddress address) {
this.address = address;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withConnectionTimeoutMillis(final long connectionTimeoutMillis) {
this.connectionTimeoutMillis = connectionTimeoutMillis;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withProtocol(
final NetconfClientConfiguration.NetconfClientProtocol clientProtocol) {
this.clientProtocol = clientProtocol;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withAdditionalHeader(
final NetconfHelloMessageAdditionalHeader additionalHeader) {
this.additionalHeader = additionalHeader;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withSessionListener(final NetconfClientSessionListener sessionListener) {
this.sessionListener = sessionListener;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withReconnectStrategy(final ReconnectStrategy reconnectStrategy) {
this.reconnectStrategy = reconnectStrategy;
return this;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfClientConfigurationBuilder withAuthHandler(final AuthenticationHandler authHandler) {
this.authHandler = authHandler;
return this;
import org.opendaylight.protocol.framework.ReconnectStrategy;
import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
-public class NetconfReconnectingClientConfigurationBuilder extends NetconfClientConfigurationBuilder {
+public final class NetconfReconnectingClientConfigurationBuilder extends NetconfClientConfigurationBuilder {
private ReconnectStrategyFactory connectStrategyFactory;
return new NetconfReconnectingClientConfigurationBuilder();
}
-
+ @SuppressWarnings("checkstyle:hiddenField")
public NetconfReconnectingClientConfigurationBuilder withConnectStrategyFactory(
final ReconnectStrategyFactory connectStrategyFactory) {
this.connectStrategyFactory = connectStrategyFactory;
}
private Channel mockChannel() {
- Channel channel = mock(Channel.class);
+ Channel ret = mock(Channel.class);
ChannelHandler channelHandler = mockChannelHandler();
- doReturn("").when(channel).toString();
- doReturn(future).when(channel).close();
- doReturn(future).when(channel).writeAndFlush(anyObject());
- doReturn(true).when(channel).isOpen();
- doReturn(pipeline).when(channel).pipeline();
+ doReturn("").when(ret).toString();
+ doReturn(future).when(ret).close();
+ doReturn(future).when(ret).writeAndFlush(anyObject());
+ doReturn(true).when(ret).isOpen();
+ doReturn(pipeline).when(ret).pipeline();
doReturn("").when(pipeline).toString();
doReturn(pipeline).when(pipeline).remove(any(ChannelHandler.class));
doReturn(channelHandler).when(pipeline).remove(anyString());
- return channel;
+ return ret;
}
private static ChannelFuture mockChannelFuture() {
negotiator.channelActive(null);
Set<String> caps = Sets.newSet("exi:1.0");
- NetconfHelloMessage helloMessage = NetconfHelloMessage.createServerHello(caps, 10);
+ NetconfHelloMessage message = NetconfHelloMessage.createServerHello(caps, 10);
doAnswer(new Answer<Object>() {
@Override
ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class);
doReturn(pipeline).when(handlerContext).pipeline();
- negotiator.handleMessage(helloMessage);
+ negotiator.handleMessage(message);
Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
channelInboundHandlerAdapter.channelRead(handlerContext, new NetconfMessage(expectedResult));
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<build>
<plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <!-- This bundle works with Karaf 3 and 4.0 -->
- <Import-Package>
- org.apache.karaf.shell.commands;version="[3.0.0,4.1)",
- org.apache.karaf.shell.console;version="[3.0.0,4.1)",
- org.apache.karaf.shell.table;version="[3.0.0,4.1)",
- *
- </Import-Package>
- </instructions>
- </configuration>
- </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-public class NetconfCommandUtils {
+public final class NetconfCommandUtils {
private static final Pattern IP_PATTERN = Pattern.compile(
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
+ private NetconfCommandUtils() {
+
+ }
+
public static boolean isPortValid(final String devicePort) {
if (Strings.isNullOrEmpty(devicePort)) {
return false;
package org.opendaylight.netconf.console.utils;
-public class NetconfConsoleConstants {
+public final class NetconfConsoleConstants {
private NetconfConsoleConstants() {
throw new IllegalStateException("Instantiating utility class.");
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfConsoleUtils {
+public final class NetconfConsoleUtils {
private static final Logger LOG = LoggerFactory.getLogger(NetconfConsoleUtils.class);
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;
-public class NetconfIidFactory {
+public final class NetconfIidFactory {
private NetconfIidFactory() {
throw new IllegalStateException("Instantiating utility class.");
.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
.build();
- public static final InstanceIdentifier<Node> netconfNodeIid(final String nodeId) {
+ public static InstanceIdentifier<Node> netconfNodeIid(final String nodeId) {
return NETCONF_TOPOLOGY_IID.child(Node.class, new NodeKey(new NodeId(nodeId)));
}
}
import static org.junit.Assert.assertNotNull;
import com.google.common.collect.ImmutableList;
-import java.io.InputStream;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
@Before
public void setUp() throws Exception {
- schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
+ schemaContext = YangParserTestUtils.parseYangResources(NetconfCommandsImplTest.class,
+ "/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 SchemaService schemaService = createSchemaService();
datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
- 16, 16, "CommitFutures");
+ 16, 16, "CommitFutures", NetconfCommandsImplTest.class);
final ConcurrentDOMDataBroker cDOMDataBroker =
new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
createTopology(LogicalDatastoreType.OPERATIONAL);
- final Map map = netconfCommands.listDevices();
+ final Map<?, ?> map = netconfCommands.listDevices();
map.containsKey(NetconfConsoleConstants.NETCONF_ID);
assertTrue(map.containsKey(NODE_ID));
- final Map mapNode = (Map) map.get(NODE_ID);
+ final Map<?, ?> mapNode = (Map<?, ?>) map.get(NODE_ID);
assertBaseNodeAttributes(mapNode);
}
public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
createTopology(LogicalDatastoreType.OPERATIONAL);
- final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
+ final Map<?, ?> mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
assertTrue(mapCorrect.containsKey(NODE_ID));
- assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
+ assertBaseNodeAttributesImmutableList((Map<?, ?>) mapCorrect.get(NODE_ID));
- final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
+ final Map<?, ?> mapWrongPort = netconfCommands.showDevice(IP, "1");
assertFalse(mapWrongPort.containsKey(NODE_ID));
- final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
+ final Map<?, ?> mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
assertFalse(mapWrongIP.containsKey(NODE_ID));
- final Map mapId = netconfCommands.showDevice(NODE_ID);
+ final Map<?, ?> mapId = netconfCommands.showDevice(NODE_ID);
assertTrue(mapId.containsKey(NODE_ID));
assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
}
assertEquals(1, nodes.size());
}
- private void createTopology(LogicalDatastoreType dataStoreType)
+ private void createTopology(final LogicalDatastoreType dataStoreType)
throws TransactionCommitFailedException, TimeoutException {
final List<Node> nodes = new ArrayList<>();
final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
}
- private Node getNetconfNode(String nodeIdent, String ip, int portNumber,
- NetconfNodeConnectionStatus.ConnectionStatus cs, String notificationCapabilityPrefix) {
+ private static Node getNetconfNode(final String nodeIdent, final String ip, final int portNumber,
+ final NetconfNodeConnectionStatus.ConnectionStatus cs, final String notificationCapabilityPrefix) {
final Host host = HostBuilder.getDefaultInstance(ip);
final PortNumber port = new PortNumber(portNumber);
return nb.build();
}
- private void assertBaseNodeAttributes(Map mapNode) {
-
+ private static void assertBaseNodeAttributes(final Map<?, ?> mapNode) {
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
}
- private void assertBaseNodeAttributesImmutableList(Map mapNode) {
+ private static void assertBaseNodeAttributesImmutableList(final Map<?, ?> mapNode) {
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
}
- private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
- "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
- "/schemas/netconf-node-topology.yang");
-
- final List<InputStream> schemas = new ArrayList<>();
- for (String schemaPath : schemaPaths) {
- final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
- schemas.add(resourceAsStream);
- }
- return schemas;
- }
-
private SchemaService createSchemaService() {
return new SchemaService() {
@Override
- public void addModule(Module module) {
+ public void addModule(final Module module) {
}
@Override
- public void removeModule(Module module) {
+ public void removeModule(final Module module) {
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
LOG.info("Session {} closing", session.getSessionId());
} catch (final Exception e) {
throw new DocumentedException("Unable to properly close session "
- + getNetconfSessionIdForReporting(), DocumentedException.ErrorType.APPLICATION,
+ + getNetconfSessionIdForReporting(), e, DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR, Collections.singletonMap(
DocumentedException.ErrorSeverity.ERROR.toString(), e.getMessage()));
}
}
- private void notifyCapabilityChanged(final Capabilities capabilities) {
+ private void notifyCapabilityChanged(final Capabilities newCapabilities) {
for (NetconfMonitoringService.CapabilitiesListener listener : listeners) {
- listener.onCapabilitiesChanged(capabilities);
+ listener.onCapabilitiesChanged(newCapabilities);
listener.onSchemasChanged(getSchemas());
}
}
Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), exception.toString()));
}
- private Document executeOperationWithHighestPriority(final Document message,
- final NetconfOperationExecution netconfOperationExecution)
- throws DocumentedException {
+ private static Document executeOperationWithHighestPriority(final Document message,
+ final NetconfOperationExecution netconfOperationExecution) throws DocumentedException {
if (LOG.isDebugEnabled()) {
LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution
.netconfOperation);
return sortedPriority;
}
- private static class NetconfOperationExecution implements NetconfOperationChainedExecution {
+ private static final class NetconfOperationExecution implements NetconfOperationChainedExecution {
private final NetconfOperation netconfOperation;
private final NetconfOperationChainedExecution subsequentExecution;
ServiceTracker<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
private final NetconfOperationServiceFactoryListener factoriesListener;
- NetconfOperationServiceFactoryTracker(BundleContext context,
+ NetconfOperationServiceFactoryTracker(final BundleContext context,
final NetconfOperationServiceFactoryListener factoriesListener) {
super(context, NetconfOperationServiceFactory.class, null);
this.factoriesListener = factoriesListener;
}
@Override
- public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
+ public NetconfOperationServiceFactory addingService(
+ final ServiceReference<NetconfOperationServiceFactory> reference) {
Object property = reference.getProperty(NetconfConstants.SERVICE_NAME);
if (property != null && isMarkedForConfig(property)) {
NetconfOperationServiceFactory netconfOperationServiceFactory = super.addingService(reference);
}
@Override
- public void removedService(ServiceReference<NetconfOperationServiceFactory> reference,
- NetconfOperationServiceFactory netconfOperationServiceFactory) {
+ public void removedService(final ServiceReference<NetconfOperationServiceFactory> reference,
+ final NetconfOperationServiceFactory netconfOperationServiceFactory) {
if (netconfOperationServiceFactory != null) {
factoriesListener.onRemoveNetconfOperationServiceFactory(netconfOperationServiceFactory);
}
}
- private boolean isMarkedForConfig(Object property) {
+ private static boolean isMarkedForConfig(final Object property) {
return NetconfConstants.CONFIG_SERVICE_MARKERS.contains(property);
}
handleDeserializerException(ctx, cause);
}
- private void handleDeserializerException(final ChannelHandlerContext ctx, final Throwable cause) {
+ private static void handleDeserializerException(final ChannelHandlerContext ctx, final Throwable cause) {
final Map<String, String> info = Maps.newHashMap();
info.put("cause", cause.getMessage());
import io.netty.channel.local.LocalAddress;
import java.net.InetSocketAddress;
-import org.apache.sshd.common.SshdSocketAddress;
+import org.apache.sshd.common.util.net.SshdSocketAddress;
import org.junit.Test;
public class NetconfServerSessionNegotiatorTest {
public void testSendNotification() throws Exception {
doNothing().when(listener).onNotification(any(), any());
final Document msgDoc = XmlUtil.readXmlToDocument("<notification></notification>");
- final NetconfNotification msg = new NetconfNotification(msgDoc);
- session.sendMessage(msg);
+ final NetconfNotification notif = new NetconfNotification(msgDoc);
+ session.sendMessage(notif);
channel.runPendingTasks();
final Object o = channel.readOutbound();
- Assert.assertEquals(msg, o);
- verify(listener).onNotification(session, msg);
+ Assert.assertEquals(notif, o);
+ verify(listener).onNotification(session, notif);
}
@Test
public void testToManagementSession() throws Exception {
final NetconfHelloMessageAdditionalHeader header =
new NetconfHelloMessageAdditionalHeader(USER, HOST, PORT, TCP_TRANSPORT, SESSION_ID);
- final EmbeddedChannel channel = new EmbeddedChannel();
- final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header);
+ final EmbeddedChannel ch = new EmbeddedChannel();
+ final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header);
tcpSession.sessionUp();
final Session managementSession = tcpSession.toManagementSession();
Assert.assertEquals(new String(managementSession.getSourceHost().getValue()), HOST);
public void testToManagementSessionUnknownTransport() throws Exception {
final NetconfHelloMessageAdditionalHeader header =
new NetconfHelloMessageAdditionalHeader(USER, HOST, PORT, "http", SESSION_ID);
- final EmbeddedChannel channel = new EmbeddedChannel();
- final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header);
+ final EmbeddedChannel ch = new EmbeddedChannel();
+ final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header);
tcpSession.sessionUp();
tcpSession.toManagementSession();
}
public void testToManagementSessionIpv6() throws Exception {
final NetconfHelloMessageAdditionalHeader header =
new NetconfHelloMessageAdditionalHeader(USER, "::1", PORT, SSH_TRANSPORT, SESSION_ID);
- final EmbeddedChannel channel = new EmbeddedChannel();
- final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header);
+ final EmbeddedChannel ch = new EmbeddedChannel();
+ 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.assertTrue(NetconfMessageToXMLEncoder.class.equals(encoder.getClass()));
}
-}
\ No newline at end of file
+}
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.config.util.xml.XmlUtil;
public class DefaultCloseSessionTest {
- private void mockEventLoop(final Channel channel) {
+ private static void mockEventLoop(final Channel channel) {
final EventLoop eventLoop = mock(EventLoop.class);
doReturn(eventLoop).when(channel).eventLoop();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- final Runnable runnable = (Runnable) args[0];
- runnable.run();
- return null;
- }
+ doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ final Runnable runnable = (Runnable) args[0];
+ runnable.run();
+ return null;
}).when(eventLoop).execute(any(Runnable.class));
doReturn(true).when(eventLoop).inEventLoop();
}
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
final ChannelFuture sendFuture = mock(ChannelFuture.class);
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- ((GenericFutureListener) invocation.getArguments()[0]).operationComplete(sendFuture);
- return null;
- }
+ doAnswer(invocation -> {
+ ((GenericFutureListener) invocation.getArguments()[0]).operationComplete(sendFuture);
+ return null;
}).when(sendFuture).addListener(any(GenericFutureListener.class));
doReturn(sendFuture).when(channel).writeAndFlush(anyObject());
doReturn(true).when(sendFuture).isSuccess();
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
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;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
public class NetconfCapabilityMonitoringServiceTest {
private static final String TEST_MODULE_REV2 = "1970-01-02";
private static final Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace");
private static final String TEST_MODULE_NAME = "testModule";
- private static Date TEST_MODULE_DATE;
- private static Date TEST_MODULE_DATE2;
+ private static final Revision TEST_MODULE_DATE = Revision.of(TEST_MODULE_REV);
+ private static final Revision TEST_MODULE_DATE2 = Revision.of(TEST_MODULE_REV2);
private YangModuleCapability moduleCapability1;
private YangModuleCapability moduleCapability2;
private NetconfCapabilityMonitoringService monitoringService;
- @BeforeClass
- public static void suiteSetUp() throws Exception {
- TEST_MODULE_DATE = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV);
- TEST_MODULE_DATE2 = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2);
- }
-
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock).getNamespace();
doReturn(TEST_MODULE_NAME).when(moduleMock).getName();
- doReturn(TEST_MODULE_DATE).when(moduleMock).getRevision();
+ doReturn(java.util.Optional.of(TEST_MODULE_DATE)).when(moduleMock).getRevision();
moduleCapability1 = new YangModuleCapability(moduleMock, TEST_MODULE_CONTENT);
capabilities.add(moduleCapability1);
doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock2).getNamespace();
doReturn(TEST_MODULE_NAME).when(moduleMock2).getName();
- doReturn(TEST_MODULE_DATE2).when(moduleMock2).getRevision();
+ doReturn(java.util.Optional.of(TEST_MODULE_DATE2)).when(moduleMock2).getRevision();
moduleCapability2 = new YangModuleCapability(moduleMock2, TEST_MODULE_CONTENT2);
capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.0"));
//remove capability
monitoringService.onCapabilitiesChanged(Collections.emptySet(), testCaps);
- verify(listener, times(3)).onCapabilitiesChanged((monitoringListenerCaptor.capture()));
+ verify(listener, times(3)).onCapabilitiesChanged(monitoringListenerCaptor.capture());
verify(notificationPublisher, times(2)).onCapabilityChanged(capabilityChangeCaptor.capture());
//verify listener calls
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
}
@Override
- public int compareTo(HandlingPriority priority) {
- if (this == priority) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public int compareTo(HandlingPriority o) {
+ if (this == o) {
return 0;
}
if (isCannotHandle()) {
return -1;
}
- if (priority.isCannotHandle()) {
+ if (o.isCannotHandle()) {
return 1;
}
- if (this.priority > priority.priority) {
+ if (priority > o.priority) {
return 1;
}
- if (this.priority.equals(priority.priority)) {
+ if (priority.equals(o.priority)) {
return 0;
}
- if (this.priority < priority.priority) {
+ if (priority < o.priority) {
return -1;
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
final String errorMessage = "Get operation for netconf-state subtree failed";
LOG.warn(errorMessage, e);
- throw new DocumentedException(errorMessage, DocumentedException.ErrorType.APPLICATION,
+ throw new DocumentedException(errorMessage, e, DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR,
Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), e.getMessage()));
final Map<String, String> errorInfo = Maps.newHashMap();
errorInfo.put(DocumentedException.ErrorTag.OPERATION_FAILED.toString(), e.getMessage());
LOG.warn("Rpc error: {}", DocumentedException.ErrorTag.OPERATION_FAILED, e);
- throw new DocumentedException(e.getMessage(), DocumentedException.ErrorType.APPLICATION,
+ throw new DocumentedException(e.getMessage(), e, DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR, errorInfo);
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
- <version>0.14.0</version>
+ <version>1.6.0</version>
</dependency>
<dependency>
<groupId>openexi</groupId>
timeout = this.timer.newTimeout(new TimerTask() {
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void run(final Timeout timeout) {
synchronized (this) {
if (state != State.ESTABLISHED) {
return channel.pipeline().replace(handlerKey, handlerKey, decoder);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
throws NetconfDocumentedException;
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void write(final char[] buffer, final int offset, final int length) throws IOException {
if ((offset < 0) || (offset > buffer.length)
|| (length < 0) || ((offset + length) > buffer.length) || ((offset + length) < 0)) {
package org.opendaylight.netconf.nettyutil.handler.ssh.authentication;
import java.io.IOException;
-import org.apache.sshd.ClientSession;
+import org.apache.sshd.client.session.ClientSession;
/**
* Class providing authentication facility to SSH handler.
package org.opendaylight.netconf.nettyutil.handler.ssh.authentication;
import java.io.IOException;
-import org.apache.sshd.ClientSession;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.session.ClientSession;
/**
* Class Providing username/password authentication option to
import com.google.common.base.Strings;
import java.io.IOException;
import java.security.KeyPair;
-import org.apache.sshd.ClientSession;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.opendaylight.aaa.encrypt.PKIUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private KeyPair keyPair = null;
private static final Logger LOG = LoggerFactory.getLogger(PublicKeyAuth.class);
- public PublicKeyAuth(String username, String password, String keyPath,
+ public PublicKeyAuth(final String username, final String password, final String keyPath,
String passPhrase) {
super(username, password);
try {
package org.opendaylight.netconf.nettyutil.handler.ssh.client;
import com.google.common.base.Preconditions;
-import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.concurrent.GenericFutureListener;
import java.io.IOException;
import java.net.SocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientSession;
-import org.apache.sshd.SshClient;
+import org.apache.sshd.client.SshClient;
+import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
-import org.apache.sshd.client.future.OpenFuture;
-import org.apache.sshd.common.future.CloseFuture;
-import org.apache.sshd.common.future.SshFutureListener;
+import org.apache.sshd.client.session.ClientSession;
import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public static final SshClient DEFAULT_CLIENT;
static {
- final Map<String, String> props = new HashMap<>();
- props.put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
- props.put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
-
final SshClient c = SshClient.setUpDefaultClient();
+ c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
+ c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
- c.setProperties(props);
// TODO make configurable, or somehow reuse netty threadpool
c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
c.start();
return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
}
- private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
+ private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
- sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
- @Override
- public void operationComplete(final ConnectFuture future) {
- if (future.isConnected()) {
- handleSshSessionCreated(future, ctx);
- } else {
- handleSshSetupFailure(ctx, future.getException());
- }
+ sshConnectionFuture.addListener(future -> {
+ if (future.isConnected()) {
+ handleSshSessionCreated(future, ctx);
+ } else {
+ handleSshSetupFailure(ctx, future.getException());
}
});
}
session = future.getSession();
final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
- authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
- @Override
- public void operationComplete(final AuthFuture future) {
- if (future.isSuccess()) {
- handleSshAuthenticated(session, ctx);
- } else {
- // Exception does not have to be set in the future, add simple exception in such case
- final Throwable exception = future.getException() == null
- ? new IllegalStateException("Authentication failed") : future.getException();
- handleSshSetupFailure(ctx, exception);
- }
+ authenticateFuture.addListener(future1 -> {
+ if (future1.isSuccess()) {
+ handleSshAuthenticated(session, ctx);
+ } else {
+ // Exception does not have to be set in the future, add simple exception in such case
+ final Throwable exception = future1.getException() == null
+ ? new IllegalStateException("Authentication failed") : future1.getException();
+ handleSshSetupFailure(ctx, exception);
}
});
} catch (final IOException e) {
}
}
- private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
+ private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
try {
LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
- session.getServerVersion());
+ newSession.getServerVersion());
- channel = session.createSubsystemChannel(SUBSYSTEM);
+ channel = newSession.createSubsystemChannel(SUBSYSTEM);
channel.setStreaming(ClientChannel.Streaming.Async);
- channel.open().addListener(new SshFutureListener<OpenFuture>() {
- @Override
- public void operationComplete(final OpenFuture future) {
- if (future.isOpened()) {
- handleSshChanelOpened(ctx);
- } else {
- handleSshSetupFailure(ctx, future.getException());
- }
+ channel.open().addListener(future -> {
+ if (future.isOpened()) {
+ handleSshChanelOpened(ctx);
+ } else {
+ handleSshSetupFailure(ctx, future.getException());
}
});
// TODO we should also read from error stream and at least log from that
- sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
- @Override
- public void close() throws Exception {
- AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
- }
- }, new AsyncSshHandlerReader.ReadMsgHandler() {
- @Override
- public void onMessageRead(final ByteBuf msg) {
- ctx.fireChannelRead(msg);
- }
- }, channel.toString(), channel.getAsyncOut());
+ sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
+ msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut());
// if readAsyncListener receives immediate close,
// it will close this handler and closing this handler sets channel variable to null
if (negotiationFuture != null) {
- negotiationFutureListener = new GenericFutureListener<Future<?>>() {
- @Override
- public void operationComplete(final Future<?> future) {
- if (future.isSuccess()) {
- connectPromise.setSuccess();
- }
+ negotiationFutureListener = future -> {
+ if (future.isSuccess()) {
+ connectPromise.setSuccess();
}
};
//complete connection promise with netconf negotiation future
}
if (session != null && !session.isClosed() && !session.isClosing()) {
- session.close(false).addListener(new SshFutureListener<CloseFuture>() {
- @Override
- public void operationComplete(final CloseFuture future) {
- if (!future.isClosed()) {
- session.close(true);
- }
- session = null;
+ session.close(false).addListener(future -> {
+ if (!future.isClosed()) {
+ session.close(true);
}
+ session = null;
});
}
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoInputStream;
import org.apache.sshd.common.io.IoReadFuture;
-import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
this.readHandler = readHandler;
this.channelId = channelId;
this.asyncOut = asyncOut;
- buf = new Buffer(BUFFER_SIZE);
+ buf = new ByteArrayBuffer(BUFFER_SIZE);
asyncOut.read(buf).addListener(this);
}
readHandler.onMessageRead(msg);
// Schedule next read
- buf = new Buffer(BUFFER_SIZE);
+ buf = new ByteArrayBuffer(BUFFER_SIZE);
currentReadFuture = asyncOut.read(buf);
currentReadFuture.addListener(this);
}
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
-import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoOutputStream;
-import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.io.WritePendingException;
-import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (LOG.isTraceEnabled()) {
LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(), byteBufToString(byteBufMsg));
}
- asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() {
-
- @Override
- public void operationComplete(final IoWriteFuture future) {
- // synchronized block due to deadlock that happens on ssh window resize
- // writes and pending writes would lock the underlyinch channel session
- // window resize write would try to write the message on an already locked channelSession,
- // while the pending write was in progress from the write callback
- synchronized (asyncInLock) {
- if (LOG.isTraceEnabled()) {
- LOG.trace(
- "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
- ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
- }
-
- // Notify success or failure
- if (future.isWritten()) {
- promise.setSuccess();
- } else {
- LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
- byteBufToString(byteBufMsg), future.getException());
- promise.setFailure(future.getException());
- }
-
- // Not needed anymore, release
- byteBufMsg.release();
-
- //rescheduling message from queue after successfully sent
- if (wasPending) {
- byteBufMsg.resetReaderIndex();
- pending.remove();
- }
+ asyncIn.write(toBuffer(byteBufMsg)).addListener(future -> {
+ // synchronized block due to deadlock that happens on ssh window resize
+ // writes and pending writes would lock the underlyinch channel session
+ // window resize write would try to write the message on an already locked channelSession,
+ // while the pending write was in progress from the write callback
+ synchronized (asyncInLock) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
+ ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
}
- // Check pending queue and schedule next
- // At this time we are guaranteed that we are not in pending state anymore
- // so the next request should succeed
- writePendingIfAny();
+ // Notify success or failure
+ if (future.isWritten()) {
+ promise.setSuccess();
+ } else {
+ LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
+ byteBufToString(byteBufMsg), future.getException());
+ promise.setFailure(future.getException());
+ }
+
+ // Not needed anymore, release
+ byteBufMsg.release();
+
+ //rescheduling message from queue after successfully sent
+ if (wasPending) {
+ byteBufMsg.resetReaderIndex();
+ pending.remove();
+ }
}
+
+ // Check pending queue and schedule next
+ // At this time we are guaranteed that we are not in pending state anymore
+ // so the next request should succeed
+ writePendingIfAny();
});
} catch (final WritePendingException e) {
msg.resetReaderIndex();
final byte[] temp = new byte[msg.readableBytes()];
msg.readBytes(temp, 0, msg.readableBytes());
- return new Buffer(temp);
+ return new ByteArrayBuffer(temp);
}
private static final class PendingWriteRequest {
@Test
public void testSendMessage() throws Exception {
final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L);
- final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
+ final NetconfHelloMessage hello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
Optional.<NetconfHelloMessageAdditionalHeader>absent());
- testingNetconfSession.sendMessage(clientHello);
- verify(channel).writeAndFlush(clientHello);
+ testingNetconfSession.sendMessage(hello);
+ verify(channel).writeAndFlush(hello);
}
-}
\ No newline at end of file
+}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import org.apache.sshd.ClientSession;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.junit.Test;
public class LoginPasswordHandlerTest {
import io.netty.channel.EventLoop;
import java.io.IOException;
import java.net.SocketAddress;
-import org.apache.sshd.ClientChannel;
-import org.apache.sshd.ClientSession;
-import org.apache.sshd.SshClient;
+import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelSubsystem;
+import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.future.OpenFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.SshFuture;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.common.io.IoReadFuture;
import org.apache.sshd.common.io.IoWriteFuture;
-import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
public class AsyncSshHandlerTest {
private static <T extends SshFuture<T>> ListenableFuture<SshFutureListener<T>> stubAddListener(final T future) {
final SettableFuture<SshFutureListener<T>> listenerSettableFuture = SettableFuture.create();
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- listenerSettableFuture.set((SshFutureListener<T>) invocation.getArguments()[0]);
- return null;
- }
+ doAnswer(invocation -> {
+ listenerSettableFuture.set((SshFutureListener<T>) invocation.getArguments()[0]);
+ return null;
}).when(future).addListener(any(SshFutureListener.class));
return listenerSettableFuture;
doReturn(Boolean.TRUE).when(eventLoop).inEventLoop();
}
- private void stubSshClient() {
+ private void stubSshClient() throws IOException {
doNothing().when(sshClient).start();
final ConnectFuture connectFuture = mock(ConnectFuture.class);
Futures.addCallback(stubAddListener(connectFuture), new SuccessFutureListener<ConnectFuture>() {
doReturn(null).when(ioReadFuture).getException();
doReturn(ioReadFuture).when(ioReadFuture).removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
doReturn(5).when(ioReadFuture).getRead();
- doReturn(new Buffer(new byte[]{0, 1, 2, 3, 4})).when(ioReadFuture).getBuffer();
+ doReturn(new ByteArrayBuffer(new byte[]{0, 1, 2, 3, 4})).when(ioReadFuture).getBuffer();
doReturn(ioReadFuture).when(ioReadFuture).addListener(Matchers.<SshFutureListener<IoReadFuture>>any());
// Always success for read
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.opendaylight.netconf.api.NetconfServerDispatcher;
import org.opendaylight.netconf.auth.AuthProvider;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
sshProxyServerConfigurationBuilder.setLocalAddress(localAddress);
sshProxyServerConfigurationBuilder.setAuthenticator(authProvider);
sshProxyServerConfigurationBuilder.setIdleTimeout(Integer.MAX_VALUE);
- sshProxyServerConfigurationBuilder.setKeyPairProvider(new PEMGeneratorHostKeyProvider(DEFAULT_PRIVATE_KEY_PATH,
- DEFAULT_ALGORITHM, DEFAULT_KEY_SIZE));
+ sshProxyServerConfigurationBuilder.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
localServer.addListener(future -> {
if (future.isDone() && !future.isCancelled()) {
return new InetSocketAddress(inetAd, Integer.parseInt(portNumber));
}
- public void close() {
+ public void close() throws IOException {
sshProxyServer.close();
if (localServer.isDone()) {
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setIoInputStream(final IoInputStream in) {
this.in = in;
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setIoOutputStream(final IoOutputStream out) {
this.out = out;
}
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setInputStream(final InputStream in) {
throw new UnsupportedOperationException("Synchronous IO is unsupported");
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setOutputStream(final OutputStream out) {
throw new UnsupportedOperationException("Synchronous IO is unsupported");
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setExitCallback(final ExitCallback callback) {
this.callback = callback;
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import org.apache.sshd.SshServer;
-import org.apache.sshd.common.Cipher;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.RuntimeSshException;
-import org.apache.sshd.common.cipher.ARCFOUR128;
-import org.apache.sshd.common.cipher.ARCFOUR256;
+import org.apache.sshd.common.cipher.BuiltinCiphers;
+import org.apache.sshd.common.cipher.Cipher;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoConnector;
import org.apache.sshd.common.io.IoHandler;
import org.apache.sshd.common.io.nio2.Nio2Acceptor;
import org.apache.sshd.common.io.nio2.Nio2Connector;
import org.apache.sshd.common.io.nio2.Nio2ServiceFactoryFactory;
-import org.apache.sshd.common.util.CloseableUtils;
+import org.apache.sshd.common.util.closeable.AbstractCloseable;
import org.apache.sshd.server.ServerFactoryManager;
+import org.apache.sshd.server.SshServer;
/**
* Proxy SSH server that just delegates decrypted content to a delegate server within same VM.
* Implemented using Apache Mina SSH lib.
*/
public class SshProxyServer implements AutoCloseable {
-
- private static final ARCFOUR128.Factory DEFAULT_ARCFOUR128_FACTORY = new ARCFOUR128.Factory();
- private static final ARCFOUR256.Factory DEFAULT_ARCFOUR256_FACTORY = new ARCFOUR256.Factory();
private final SshServer sshServer;
private final ScheduledExecutorService minaTimerExecutor;
private final EventLoopGroup clientGroup;
//remove rc4 ciphers
final List<NamedFactory<Cipher>> cipherFactories = sshServer.getCipherFactories();
- cipherFactories.removeIf(factory -> factory.getName().contains(DEFAULT_ARCFOUR128_FACTORY.getName())
- || factory.getName().contains(DEFAULT_ARCFOUR256_FACTORY.getName()));
+ cipherFactories.removeIf(factory -> factory.getName().contains(BuiltinCiphers.arcfour128.getName())
+ || factory.getName().contains(BuiltinCiphers.arcfour256.getName()));
sshServer.setPasswordAuthenticator(
(username, password, session)
-> sshProxyServerConfiguration.getAuthenticator().authenticated(username, password));
sshServer.setIoServiceFactoryFactory(nioServiceWithPoolFactoryFactory);
sshServer.setScheduledExecutorService(minaTimerExecutor);
- sshServer.setProperties(getProperties(sshProxyServerConfiguration));
+ sshServer.getProperties().put(ServerFactoryManager.IDLE_TIMEOUT,
+ String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
+ sshServer.getProperties().put(ServerFactoryManager.AUTH_TIMEOUT,
+ String.valueOf(sshProxyServerConfiguration.getIdleTimeout()));
final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory =
new RemoteNetconfCommand.NetconfCommandFactory(clientGroup,
}
@Override
- public void close() {
+ public void close() throws IOException {
try {
sshServer.stop(true);
- } catch (final InterruptedException e) {
- throw new RuntimeException("Interrupted while stopping sshServer", e);
} finally {
sshServer.close(true);
}
/**
* Based on Nio2ServiceFactory with one addition: injectable executor.
*/
- private static final class NioServiceWithPoolFactory
- extends CloseableUtils.AbstractCloseable implements IoServiceFactory {
+ private static final class NioServiceWithPoolFactory extends AbstractCloseable implements IoServiceFactory {
private final FactoryManager manager;
private final AsynchronousChannelGroup group;
import io.netty.channel.local.LocalAddress;
import java.net.InetSocketAddress;
import java.util.Optional;
-import org.apache.sshd.common.KeyPairProvider;
-import org.apache.sshd.server.PublickeyAuthenticator;
+import org.apache.sshd.common.keyprovider.KeyPairProvider;
+import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.opendaylight.netconf.auth.AuthProvider;
public final class SshProxyServerConfiguration {
* 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.ssh;
import io.netty.channel.local.LocalAddress;
import java.net.InetSocketAddress;
-import org.apache.sshd.common.KeyPairProvider;
-import org.apache.sshd.server.PublickeyAuthenticator;
+import org.apache.sshd.common.keyprovider.KeyPairProvider;
+import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.opendaylight.netconf.auth.AuthProvider;
public final class SshProxyServerConfigurationBuilder {
private AuthProvider authenticator;
private KeyPairProvider keyPairProvider;
private int idleTimeout;
- private PublickeyAuthenticator publicKeyAuthenticator = null;
+ private PublickeyAuthenticator publickeyAuthenticator = null;
public SshProxyServerConfigurationBuilder setBindingAddress(final InetSocketAddress bindingAddress) {
this.bindingAddress = bindingAddress;
return this;
}
- public SshProxyServerConfigurationBuilder setPublickeyAuthenticator(final PublickeyAuthenticator authenticator) {
- this.publicKeyAuthenticator = authenticator;
+ public SshProxyServerConfigurationBuilder setPublickeyAuthenticator(
+ final PublickeyAuthenticator publickeyAuthenticator) {
+ this.publickeyAuthenticator = publickeyAuthenticator;
return this;
}
}
public SshProxyServerConfiguration createSshProxyServerConfiguration() {
- return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, publicKeyAuthenticator,
+ return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, publickeyAuthenticator,
keyPairProvider, idleTimeout);
}
public static SshProxyServerConfigurationBuilder create() {
return new SshProxyServerConfigurationBuilder();
}
-}
\ No newline at end of file
+}
import io.netty.channel.local.LocalAddress;
import io.netty.channel.nio.NioEventLoopGroup;
+import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
-import org.apache.sshd.common.util.ThreadUtils;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.common.util.security.SecurityUtils;
+import org.apache.sshd.common.util.threads.ThreadUtils;
+import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider;
import org.opendaylight.netconf.ssh.SshProxyServer;
import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
LOG.trace("Starting netconf SSH server with path to ssh private key {}", path);
final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerExecutor, clientGroup, nioExecutor);
+ final AbstractGeneratorHostKeyProvider keyPairProvider = SecurityUtils.createGeneratorHostKeyProvider(null);
+ keyPairProvider.setAlgorithm(ALGORITHM);
+ keyPairProvider.setKeySize(KEY_SIZE);
+ keyPairProvider.setFile(new File(path));
sshProxyServer.bind(
new SshProxyServerConfigurationBuilder()
.setBindingAddress(sshSocketAddress)
.setLocalAddress(localAddress)
.setAuthenticator(authProviderTracker)
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(path, ALGORITHM, KEY_SIZE))
+ .setKeyPairProvider(keyPairProvider)
.setIdleTimeout(DEFAULT_IDLE_TIMEOUT)
.createSshProxyServerConfiguration());
return sshProxyServer;
public class EchoClientHandler extends ChannelInboundHandlerAdapter implements ChannelFutureListener {
private static final Logger LOG = LoggerFactory.getLogger(EchoClientHandler.class);
- private ChannelHandlerContext ctx;
+ private ChannelHandlerContext context;
private final StringBuilder fromServer = new StringBuilder();
public enum State {
@Override
public synchronized void channelActive(ChannelHandlerContext ctx) {
- checkState(this.ctx == null);
+ checkState(context == null);
LOG.info("channelActive");
- this.ctx = ctx;
+ context = ctx;
state = State.CONNECTED;
}
public synchronized void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
LOG.warn("Unexpected exception from downstream.", cause);
- checkState(this.ctx.equals(ctx));
+ checkState(context.equals(ctx));
ctx.close();
- this.ctx = null;
+ context = null;
}
public synchronized void write(String message) {
ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes());
- ctx.writeAndFlush(byteBuf);
+ context.writeAndFlush(byteBuf);
}
public synchronized boolean isConnected() {
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.common.util.security.SecurityUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
sshProxyServer.bind(new SshProxyServerConfigurationBuilder()
.setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
.setAuthenticator((username, password) -> true)
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString(),
- "RSA", 4096))
+ .setKeyPairProvider(SecurityUtils.createGeneratorHostKeyProvider(sshKeyPair.toPath()))
.setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
final EchoClientHandler echoClientHandler = connectClient(addr);
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import org.apache.sshd.ClientSession;
-import org.apache.sshd.SshClient;
+import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.util.security.SecurityUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
server.bind(new SshProxyServerConfigurationBuilder()
.setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
.setAuthenticator((username, password) -> true)
- .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString(),
- "RSA", 4096))
+ .setKeyPairProvider(SecurityUtils.createGeneratorHostKeyProvider(sshKeyPair.toPath()))
.setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
LOG.info("SSH server started on {}", PORT);
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
- <artifactId>akka-actor_${scala.version}</artifactId>
+ <artifactId>akka-actor_2.12</artifactId>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
- <artifactId>akka-cluster_${scala.version}</artifactId>
+ <artifactId>akka-cluster_2.12</artifactId>
</dependency>
<dependency>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
- <artifactId>akka-testkit_${scala.version}</artifactId>
+ <artifactId>akka-testkit_2.12</artifactId>
</dependency>
</dependencies>
import akka.dispatch.OnComplete;
import akka.pattern.Patterns;
import akka.util.Timeout;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.stream.Collectors;
import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalProvider;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;
private final ActorRef masterActorRef;
private final ActorSystem actorSystem;
- private SchemaContext remoteSchemaContext = null;
+ private SchemaContext currentSchemaContext = null;
private NetconfSessionPreferences netconfSessionPreferences = null;
private DOMRpcService deviceRpc = null;
private DOMDataBroker deviceDataBroker = null;
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onDeviceConnected(final SchemaContext remoteSchemaContext,
final NetconfSessionPreferences netconfSessionPreferences,
final DOMRpcService deviceRpc) {
- this.remoteSchemaContext = remoteSchemaContext;
+ this.currentSchemaContext = remoteSchemaContext;
this.netconfSessionPreferences = netconfSessionPreferences;
this.deviceRpc = deviceRpc;
private void registerMasterMountPoint() {
Preconditions.checkNotNull(id);
- Preconditions.checkNotNull(remoteSchemaContext,
+ Preconditions.checkNotNull(currentSchemaContext,
"Device has no remote schema context yet. Probably not fully connected.");
Preconditions.checkNotNull(netconfSessionPreferences,
"Device has no capabilities yet. Probably not fully connected.");
LOG.info("{}: Creating master data broker for device", id);
- deviceDataBroker = new NetconfDeviceDataBroker(id, remoteSchemaContext, deviceRpc, netconfSessionPreferences);
+ deviceDataBroker = new NetconfDeviceDataBroker(id, currentSchemaContext, deviceRpc, netconfSessionPreferences);
// We need to create ProxyDOMDataBroker so accessing mountpoint
// on leader node would be same as on follower node
final ProxyDOMDataBroker proxyDataBroker =
new ProxyDOMDataBroker(actorSystem, id, masterActorRef, actorResponseWaitTime);
salProvider.getMountInstance()
- .onTopologyDeviceConnected(remoteSchemaContext, proxyDataBroker, deviceRpc, notificationService);
+ .onTopologyDeviceConnected(currentSchemaContext, proxyDataBroker, deviceRpc, notificationService);
}
private Future<Object> sendInitialDataToActor() {
final List<SourceIdentifier> sourceIdentifiers =
- remoteSchemaContext.getAllModuleIdentifiers().stream().map(mi ->
- RevisionSourceIdentifier.create(mi.getName(),
- (SimpleDateFormatUtil.DEFAULT_DATE_REV == mi.getRevision() ? Optional.<String>absent() :
- Optional.of(mi.getQNameModule().getFormattedRevision()))))
- .collect(Collectors.toList());
+ SchemaContextUtil.getConstituentModuleIdentifiers(currentSchemaContext).stream()
+ .map(mi -> RevisionSourceIdentifier.create(mi.getName(), mi.getRevision()))
+ .collect(Collectors.toList());
// send initial data to master actor and create actor for providing it
return Patterns.ask(masterActorRef, new CreateInitialMasterActorData(deviceDataBroker, sourceIdentifiers,
// Blueprint init method
public void init() {
- dataChangeListenerRegistration = registerDataTreeChangeListener(topologyId);
+ dataChangeListenerRegistration = registerDataTreeChangeListener();
}
@Override
this.privateKeyPassphrase = privateKeyPassphrase;
}
- private ListenerRegistration<NetconfTopologyManager> registerDataTreeChangeListener(final String topologyId) {
+ private ListenerRegistration<NetconfTopologyManager> registerDataTreeChangeListener() {
final WriteTransaction wtx = dataBroker.newWriteOnlyTransaction();
- initTopology(wtx, LogicalDatastoreType.CONFIGURATION, topologyId);
- initTopology(wtx, LogicalDatastoreType.OPERATIONAL, topologyId);
+ initTopology(wtx, LogicalDatastoreType.CONFIGURATION);
+ initTopology(wtx, LogicalDatastoreType.OPERATIONAL);
Futures.addCallback(wtx.submit(), new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
}
- private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType,
- final String topologyId) {
+ private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType) {
final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
final InstanceIdentifier<NetworkTopology> networkTopologyId =
InstanceIdentifier.builder(NetworkTopology.class).build();
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider;
import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
-public class NetconfNodeActor extends UntypedActor {
+public final class NetconfNodeActor extends UntypedActor {
private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeActor.class);
}
} else if (message instanceof InvokeRpcMessage) { // master
- final InvokeRpcMessage invokeRpcMessage = ((InvokeRpcMessage) message);
+ final InvokeRpcMessage invokeRpcMessage = (InvokeRpcMessage) message;
invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender());
} else if (message instanceof RegisterMountPoint) { //slaves
}
private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> yangTextSchemaSource =
+ final ListenableFuture<@NonNull YangTextSchemaSource> yangTextSchemaSource =
schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
Futures.addCallback(yangTextSchemaSource, new FutureCallback<YangTextSchemaSource>() {
slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime,
mountPointService);
- final CheckedFuture<SchemaContext, SchemaResolutionException> remoteSchemaContext =
- getSchemaContext(masterReference);
- final DOMRpcService deviceRpc = getDOMRpcService(masterReference);
+ final ListenableFuture<SchemaContext> remoteSchemaContext = getSchemaContext(masterReference);
+ final DOMRpcService deviceRpcService = getDOMRpcService(masterReference);
Futures.addCallback(remoteSchemaContext, new FutureCallback<SchemaContext>() {
@Override
public void onSuccess(final SchemaContext result) {
LOG.info("{}: Schema context resolved: {}", id, result.getModules());
- slaveSalManager.registerSlaveMountPoint(result, deviceRpc, masterReference);
+ slaveSalManager.registerSlaveMountPoint(result, deviceRpcService, masterReference);
}
@Override
return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
}
- private CheckedFuture<SchemaContext, SchemaResolutionException> getSchemaContext(final ActorRef masterReference) {
+ private ListenableFuture<SchemaContext> getSchemaContext(final ActorRef masterReference) {
final RemoteYangTextSourceProvider remoteYangTextSourceProvider =
new ProxyYangTextSourceProvider(masterReference, getContext(), actorResponseWaitTime);
/**
* ReadTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes.
*/
-public class ReadTransactionActor extends UntypedActor {
+public final class ReadTransactionActor extends UntypedActor {
private final ReadAdapter readAdapter;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
-public class ReadWriteTransactionActor extends UntypedActor {
+public final class ReadWriteTransactionActor extends UntypedActor {
private static final Logger LOG = LoggerFactory.getLogger(ReadWriteTransactionActor.class);
/**
* WriteTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes.
*/
-public class WriteTransactionActor extends UntypedActor {
+public final class WriteTransactionActor extends UntypedActor {
private static final Logger LOG = LoggerFactory.getLogger(WriteTransactionActor.class);
private final String privateKeyPassphrase;
private final AAAEncryptionService encryptionService;
- private NetconfTopologySetup(final NetconfTopologySetupBuilder builder) {
+ NetconfTopologySetup(final NetconfTopologySetupBuilder builder) {
this.clusterSingletonServiceProvider = builder.getClusterSingletonServiceProvider();
this.rpcProviderRegistry = builder.getRpcProviderRegistry();
this.dataBroker = builder.getDataBroker();
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfTopologyUtils {
+public final class NetconfTopologyUtils {
private static Logger LOG = LoggerFactory.getLogger(NetconfTopologyUtils.class);
private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
}
+ private NetconfTopologyUtils() {
+
+ }
+
public static NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final Node node) {
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
final String moduleSchemaCacheDirectory = netconfNode.getSchemaCacheDirectory();
import akka.testkit.TestActorRef;
import akka.util.Timeout;
import com.google.common.base.MoreObjects;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.net.InetAddresses;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
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.PotentialSchemaSource;
final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
final List<SourceIdentifier> sourceIdentifiers =
- Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
+ Lists.newArrayList(RevisionSourceIdentifier.create("testID"));
// init master data
final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2");
final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class);
final SchemaRepository schemaRepository = mock(SchemaRepository.class);
- final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class);
- final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class);
+ final SchemaSourceRegistration<?> regYang1 = mock(SchemaSourceRegistration.class);
+ final SchemaSourceRegistration<?> regYang2 = mock(SchemaSourceRegistration.class);
doReturn(regYang1).when(registry).registerSchemaSource(any(), withSourceId(yang1));
doReturn(regYang2).when(registry).registerSchemaSource(any(), withSourceId(yang2));
final SchemaContextFactory schemaContextFactory = mock(SchemaContextFactory.class);
- doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any());
+ doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any(SchemaSourceFilter.class));
final SettableFuture<SchemaContext> schemaContextFuture = SettableFuture.create();
final CheckedFuture<SchemaContext, SchemaResolutionException> checkedFuture =
Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e));
@Test
public void testYangTextSchemaSourceRequestMessage() throws Exception {
final SchemaRepository schemaRepository = mock(SchemaRepository.class);
- final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent());
+ final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID");
final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId,
DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService);
};
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> result =
- Futures.immediateCheckedFuture(yangTextSchemaSource);
+ final ListenableFuture<YangTextSchemaSource> result = Futures.immediateFuture(yangTextSchemaSource);
doReturn(result).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
final List<SourceIdentifier> sourceIdentifiers =
- Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
+ Lists.newArrayList(RevisionSourceIdentifier.create("testID"));
// init master data
final ProxyDOMRpcService slaveDomRPCService =
new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
- final SchemaPath schemaPath = SchemaPath.create(true, QName.create("TestQname"));
+ final QName testQName = QName.create("", "TestQname");
+ final SchemaPath schemaPath = SchemaPath.create(true, testQName);
final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(testQName))
+ .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, null, "Rpc invocation failed.");
// EmptyResultResponse message
.setKeepaliveDelay(1L)
.build();
- final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID,
- new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
@Test
public void testRead() throws Exception {
final ContainerNode node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
when(deviceReadTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import scala.concurrent.Await;
import scala.concurrent.Future;
private TestProbe probe;
private ActorSystem system;
private TestActorRef<WriteTransactionActor> actorRef;
- private NormalizedNode<?, ?> node;
+ private ContainerNode node;
@Before
public void setUp() throws Exception {
system = ActorSystem.apply();
probe = TestProbe.apply(system);
node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
actorRef = TestActorRef.create(system, ReadWriteTransactionActor.props(deviceReadWriteTx,
Duration.apply(2, TimeUnit.SECONDS)), "testA");
@Test
public void testRead() throws Exception {
- final ContainerNode node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
- .build();
when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
verify(deviceReadWriteTx).read(STORE, PATH);
@Test
public void testIdleTimeout() throws Exception {
- final TestProbe probe = new TestProbe(system);
- probe.watch(actorRef);
+ final TestProbe testProbe = new TestProbe(system);
+ testProbe.watch(actorRef);
verify(deviceReadWriteTx, timeout(3000)).cancel();
- probe.expectTerminated(actorRef, TIMEOUT.duration());
+ testProbe.expectTerminated(actorRef, TIMEOUT.duration());
}
-}
\ No newline at end of file
+}
system = ActorSystem.apply();
probe = TestProbe.apply(system);
node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
actorRef = TestActorRef.create(system, WriteTransactionActor.props(deviceWriteTx,
Duration.apply(2, TimeUnit.SECONDS)), "testA");
@Test
public void testIdleTimeout() throws Exception {
- final TestProbe probe = new TestProbe(system);
- probe.watch(actorRef);
+ final TestProbe testProbe = new TestProbe(system);
+ testProbe.watch(actorRef);
verify(deviceWriteTx, timeout(3000)).cancel();
- probe.expectTerminated(actorRef, TIMEOUT.duration());
+ testProbe.expectTerminated(actorRef, TIMEOUT.duration());
}
-}
\ No newline at end of file
+}
masterActor = new TestProbe(system);
final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830));
node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
tx = new ProxyReadTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS));
}
masterActor = new TestProbe(system);
final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830));
node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
tx = new ProxyReadWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS));
}
masterActor = new TestProbe(system);
final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830));
node = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
.build();
tx = new ProxyWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS));
}
@Test
public void testCancelSubmitted() throws Exception {
- final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ final ListenableFuture<Void> submitFuture = tx.submit();
masterActor.expectMsgClass(SubmitRequest.class);
masterActor.reply(new SubmitReply());
- submitFuture.checkedGet();
+ submitFuture.get();
final Future<Boolean> submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel());
masterActor.expectNoMsg();
Assert.assertFalse(submit.get());
@Test
public void testSubmit() throws Exception {
- final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ final ListenableFuture<Void> submitFuture = tx.submit();
masterActor.expectMsgClass(SubmitRequest.class);
masterActor.reply(new SubmitReply());
- submitFuture.checkedGet();
+ submitFuture.get();
}
@Test
public void testDoubleSubmit() throws Exception {
- final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ final ListenableFuture<Void> submitFuture = tx.submit();
masterActor.expectMsgClass(SubmitRequest.class);
masterActor.reply(new SubmitReply());
- submitFuture.checkedGet();
+ submitFuture.get();
try {
tx.submit().checkedGet();
Assert.fail("Should throw IllegalStateException");
public void testRead() throws Exception {
// Message: NormalizedNodeMessage
final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build();
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
Futures.immediateCheckedFuture(Optional.of(outputNode));
doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier);
instanceIdentifier);
final Optional<NormalizedNode<?, ?>> resultEmptyMessage =
- resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+ resultEmptyResponse.get(TIMEOUT_SEC, TimeUnit.SECONDS);
assertEquals(resultEmptyMessage, Optional.absent());
}
new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
initializeDataTest();
testNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build();
instanceIdentifier = YangInstanceIdentifier.EMPTY;
storeType = LogicalDatastoreType.CONFIGURATION;
}
@Test
public void testDelete() throws Exception {
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-
// Test of invoking delete on master through slave proxy
final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
- wTx.delete(storeType, instanceIdentifier);
+ wTx.delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
wTx.cancel();
- verify(readWriteTx, timeout(2000)).delete(storeType, instanceIdentifier);
+ verify(readWriteTx, timeout(2000)).delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
}
@Test
public void testRead() throws Exception {
// Message: NormalizedNodeMessage
final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build();
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
Futures.immediateCheckedFuture(Optional.of(outputNode));
doReturn(resultNormalizedNodeMessage).when(readWriteTx).read(storeType, instanceIdentifier);
new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
initializeDataTest();
testNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build();
instanceIdentifier = YangInstanceIdentifier.EMPTY;
storeType = LogicalDatastoreType.CONFIGURATION;
}
@Test
public void testDelete() throws Exception {
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-
// Test of invoking delete on master through slave proxy
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
- wTx.delete(storeType, instanceIdentifier);
+ wTx.delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
wTx.cancel();
- verify(writeTx, timeout(2000)).delete(storeType, instanceIdentifier);
+ verify(writeTx, timeout(2000)).delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
}
@Test
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
- final SchemaContextFactory schemaContextFactory
+ final SchemaContextFactory contextFactory
= repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
setSchemaRegistry(repository);
- setSchemaContextFactory(schemaContextFactory);
+ setSchemaContextFactory(contextFactory);
final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
createDeviceFilesystemCache(moduleSchemaCacheDirectory);
repository.registerSchemaSourceListener(deviceCache);
- return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
+ return new NetconfDevice.SchemaResourcesDTO(repository, repository, contextFactory,
new NetconfStateSchemasResolverImpl());
}
/**
* Sets the private key path from location specified in configuration file using blueprint.
*/
- public void setPrivateKeyPath(String privateKeyPath) {
+ public void setPrivateKeyPath(final String privateKeyPath) {
this.privateKeyPath = privateKeyPath;
}
/**
* Sets the private key passphrase from location specified in configuration file using blueprint.
*/
- public void setPrivateKeyPassphrase(String privateKeyPassphrase) {
+ public void setPrivateKeyPassphrase(final String privateKeyPassphrase) {
this.privateKeyPassphrase = privateKeyPassphrase;
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
* 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.util;
-public class CloseableUtil {
+public final class CloseableUtil {
+ private CloseableUtil() {
+
+ }
@SuppressWarnings("checkstyle:IllegalCatch")
public static void closeAll(Iterable<? extends AutoCloseable> autoCloseables) throws Exception {
/**
* See <a href="http://tools.ietf.org/html/rfc6241#section-6">rfc6241</a> for details.
*/
-public class SubtreeFilter {
+public final class SubtreeFilter {
private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
+ private SubtreeFilter() {
+
+ }
+
public static Document applyRpcSubtreeFilter(Document requestDocument,
Document rpcReply) throws DocumentedException {
OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument);
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
-public class XmlFileLoader {
+public final class XmlFileLoader {
+
+ private XmlFileLoader() {
+
+ }
public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException,
ParserConfigurationException {
import org.w3c.dom.Node;
import org.w3c.dom.Text;
-public class XmlUnitUtil {
+public final class XmlUnitUtil {
private XmlUnitUtil() {}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
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.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
* Holds URLs with YANG schema resources for all yang modules reported in
* ietf-netconf-yang-library/modules-state/modules node.
*/
-public class LibraryModulesSchemas implements NetconfDeviceSchemas {
+public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
final Map<SourceIdentifier, URL> result = Maps.newHashMap();
for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
final SourceIdentifier sId = RevisionSourceIdentifier
- .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
+ .create(entry.getKey().getLocalName(), entry.getKey().getRevision());
result.put(sId, entry.getValue());
}
if (modulesStateNode.isPresent()) {
Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
"Expecting container containing schemas, but was %s", modulesStateNode.get());
- return create(((ContainerNode) modulesStateNode.get()));
- } else {
- LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ return create((ContainerNode) modulesStateNode.get());
}
+
+ LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
+ return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
}
private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
if (result == null) {
- return Optional.absent();
+ return Optional.empty();
}
final Optional<DataContainerChild<?, ?>> dataNode =
((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
if (dataNode.isPresent() == false) {
- return Optional.absent();
+ return Optional.empty();
}
return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
jsonParser.parse(reader);
- return resultHolder.isFinished()
- ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
+ return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
}
@SuppressWarnings("checkstyle:IllegalCatch")
LOG.warn("Unable to parse yang library xml content", e);
}
- return Optional.<NormalizedNode<?, ?>>absent();
+ return Optional.empty();
}
private static Optional<Map.Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
if (revision.isPresent()) {
- if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
+ if (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) {
LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
- return Optional.<Map.Entry<QName, URL>>absent();
+ return Optional.empty();
}
}
final QName moduleQName = revision.isPresent()
? QName.create(moduleNameSpace, revision.get(), moduleName)
- : QName.create(URI.create(moduleNameSpace), null, moduleName);
+ : QName.create(URI.create(moduleNameSpace), moduleName);
try {
return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
} catch (final MalformedURLException e) {
LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
moduleNode, schemaUriAsString.get());
- return Optional.<Map.Entry<QName, URL>>absent();
+ return Optional.empty();
}
}
private static Optional<String> getValueOfSimpleNode(
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString())
- ? Optional.<String>absent() : Optional.of(value.toString().trim());
+ return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty()
+ : Optional.of(value.toString().trim());
}
@Override
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
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.model.repo.spi.SchemaSourceRegistration;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
private static SourceIdentifier toSourceId(final QName input) {
- return RevisionSourceIdentifier.create(input.getLocalName(),
- Optional.fromNullable(input.getFormattedRevision()));
+ return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
}
}
}
private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
-
return requiredSources.parallelStream().filter(sourceIdentifier -> {
- boolean remove = false;
try {
- schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
- } catch (SchemaSourceException e) {
- remove = true;
+ schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).get();
+ return false;
+ } catch (InterruptedException | ExecutionException e) {
+ return true;
}
- return remove;
}).collect(Collectors.toList());
}
while (!requiredSources.isEmpty()) {
LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
try {
- final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture =
- schemaContextFactory.createSchemaContext(requiredSources);
- final SchemaContext result = schemaBuilderFuture.checkedGet();
+ final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
+ .createSchemaContext(requiredSources);
+ final SchemaContext result = schemaBuilderFuture.get();
LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
capabilities.getUnresolvedCapabilites().keySet());
handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
return;
- } catch (final SchemaResolutionException e) {
+ } catch (final ExecutionException e) {
// schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
// that might be wrapping a MissingSchemaSourceException so we need to look
// at the cause of the exception to make sure we don't misinterpret it.
- if (e.getCause() instanceof MissingSchemaSourceException) {
+ final Throwable cause = e.getCause();
+
+ if (cause instanceof MissingSchemaSourceException) {
requiredSources = handleMissingSchemaSourceException(
requiredSources, (MissingSchemaSourceException) e.getCause());
continue;
}
- requiredSources = handleSchemaResolutionException(requiredSources, e);
+ if (cause instanceof SchemaResolutionException) {
+ requiredSources = handleSchemaResolutionException(requiredSources,
+ (SchemaResolutionException) cause);
+ } else {
+ handleSalInitializationFailure(e, listener);
+ return;
+ }
} catch (final Exception e) {
// unknown error, fail
handleSalInitializationFailure(e, listener);
continue;
}
- final String rev = getNullableRev(identifier);
- if (rev == null) {
- if (qname.getRevision() == null) {
- return qname;
- }
- } else if (qname.getFormattedRevision().equals(rev)) {
+ if (identifier.getRevision().equals(qname.getRevision())) {
return qname;
}
}
// this capability will be removed from required sources and not reported as unresolved-capability
return null;
}
-
- private String getNullableRev(final SourceIdentifier identifier) {
- final String rev = identifier.getRevision();
- return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? null : rev;
- }
}
}
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
import java.net.URI;
import java.util.Collections;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
if (result == null) {
- return Optional.absent();
+ return Optional.empty();
}
final Optional<DataContainerChild<?, ?>> dataNode =
((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
if (!dataNode.isPresent()) {
- return Optional.absent();
+ return Optional.empty();
}
final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
if (!nStateNode.isPresent()) {
- return Optional.absent();
+ return Optional.empty();
}
return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
if (!formatAsString.equals(Yang.QNAME.toString())) {
LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
- return Optional.absent();
+ return Optional.empty();
}
childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
- return Optional.absent();
+ return Optional.empty();
}
childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
if (!namespaceValue.isPresent()) {
LOG.warn("{}: Ignoring schema due to missing namespace", id);
- return Optional.absent();
+ return Optional.empty();
}
final String namespaceAsString = namespaceValue.get();
final QName moduleQName = revisionAsString.isPresent()
? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
- : QName.create(URI.create(namespaceAsString), null, moduleNameAsString);
+ : QName.create(URI.create(namespaceAsString), moduleNameAsString);
return Optional.of(new RemoteYangSchema(moduleQName));
}
return getValueOfSimpleNode(node.get());
} else {
LOG.debug("Child node {} not present", childNode);
- return Optional.absent();
+ return Optional.empty();
}
}
final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
final Object value = node.getValue();
return value == null || Strings.isNullOrEmpty(value.toString())
- ? Optional.<String>absent() : Optional.of(value.toString().trim());
+ ? Optional.empty() : Optional.of(value.toString().trim());
}
@Override
/**
* Forward all cached notifications and pass all notifications from this point directly to sal facade.
- * @param messageTransformer Message transformer
+ * @param transformer Message transformer
*/
- synchronized void onRemoteSchemaUp(final MessageTransformer<NetconfMessage> messageTransformer) {
- this.messageTransformer = Preconditions.checkNotNull(messageTransformer);
+ synchronized void onRemoteSchemaUp(final MessageTransformer<NetconfMessage> transformer) {
+ this.messageTransformer = Preconditions.checkNotNull(transformer);
passNotifications = true;
}
}
- synchronized void addNotificationFilter(final NotificationFilter filter) {
- this.filter = filter;
+ synchronized void addNotificationFilter(final NotificationFilter newFilter) {
+ this.filter = newFilter;
}
synchronized void onRemoteSchemaDown() {
import java.io.StringReader;
import java.security.KeyPair;
import java.util.Optional;
-import org.apache.sshd.ClientSession;
import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.session.ClientSession;
import org.opendaylight.aaa.encrypt.AAAEncryptionService;
import org.opendaylight.aaa.encrypt.PKIUtil;
import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
}
@Override
- public AuthFuture authenticate(ClientSession session) throws IOException {
+ public AuthFuture authenticate(final ClientSession session) throws IOException {
// if we have keypair set the identity, otherwise retry the retrieval from the adapter
// if successful set the identity.
if (keyPair.isPresent() || tryToSetKeyPair()) {
private final int concurentRpcMsgs;
private final Queue<Request> requests = new ArrayDeque<>();
- private NetconfClientSession session;
+ private NetconfClientSession currentSession;
private Future<?> initFuture;
private final SettableFuture<NetconfDeviceCapabilities> firstConnectionFuture;
sessionLock.lock();
try {
LOG.debug("{}: Session established", id);
- this.session = session;
+ currentSession = session;
NetconfSessionPreferences netconfSessionPreferences =
NetconfSessionPreferences.fromNetconfSession(session);
public void disconnect() {
// If session is already in closing, no need to close it again
- if (session != null && isSessionClosing.compareAndSet(false, true)) {
- session.close();
+ if (currentSession != null && isSessionClosing.compareAndSet(false, true)) {
+ currentSession.close();
}
}
final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
sessionLock.lock();
try {
- if (session != null) {
- session = null;
+ if (currentSession != null) {
+ currentSession = null;
/*
* Walk all requests, check if they have been executing
* or cancelled and remove them from the queue.
LOG.trace("{}: Sending message {}", id, msgToS(message));
}
- if (session == null) {
+ if (currentSession == null) {
LOG.warn("{}: Session is disconnected, failing RPC request {}",
id, message);
return Futures.immediateFuture(createSessionDownRpcResult());
final Request req = new Request(new UncancellableFuture<>(true), message);
requests.add(req);
- session.sendMessage(req.request).addListener(future -> {
+ currentSession.sendMessage(req.request).addListener(future -> {
if (!future.isSuccess()) {
// We expect that a session down will occur at this point
LOG.debug("{}: Failed to send request {}", id,
private final int skipLength;
ParameterMatcher(final String name) {
- predicate = new Predicate<String>() {
- @Override
- public boolean apply(final String input) {
- return input.startsWith(name);
- }
- };
+ predicate = input -> input.startsWith(name);
this.skipLength = name.length();
}
private static final ParameterMatcher REVISION_PARAM = new ParameterMatcher("revision=");
private static final ParameterMatcher BROKEN_REVISON_PARAM = new ParameterMatcher("amp;revision=");
private static final Splitter AMP_SPLITTER = Splitter.on('&');
- private static final Predicate<String> CONTAINS_REVISION = new Predicate<String>() {
- @Override
- public boolean apply(final String input) {
- return input.contains("revision=");
- }
- };
+ private static final Predicate<String> CONTAINS_REVISION = input -> input.contains("revision=");
private final Map<QName, CapabilityOrigin> moduleBasedCaps;
private final Map<String, CapabilityOrigin> nonModuleCaps;
}
private static QName cachedQName(final String namespace, final String moduleName) {
- return QName.create(URI.create(namespace), null, moduleName).withoutRevision().intern();
+ return QName.create(URI.create(namespace), moduleName).withoutRevision().intern();
}
public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities) {
*/
public final class NetconfDeviceRpc implements DOMRpcService {
- private final RemoteDeviceCommunicator<NetconfMessage> listener;
+ private final RemoteDeviceCommunicator<NetconfMessage> communicator;
private final MessageTransformer<NetconfMessage> transformer;
private final Collection<DOMRpcIdentifier> availableRpcs;
- public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener,
- final MessageTransformer<NetconfMessage> transformer) {
- this.listener = listener;
+ public NetconfDeviceRpc(final SchemaContext schemaContext,
+ final RemoteDeviceCommunicator<NetconfMessage> communicator,
+ final MessageTransformer<NetconfMessage> transformer) {
+ this.communicator = communicator;
this.transformer = transformer;
availableRpcs = Collections2.transform(schemaContext.getOperations(),
@Nullable final NormalizedNode<?, ?> input) {
final NetconfMessage message = transformer.toRpcRequest(type, input);
final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult =
- listener.sendRequest(message, type.getLastComponent());
+ communicator.sendRequest(message, type.getLastComponent());
final ListenableFuture<DOMRpcResult> transformed =
Futures.transform(delegateFutureWithPureResult, input1 -> {
}
public synchronized void onTopologyDeviceConnected(final SchemaContext initialCtx,
- final DOMDataBroker broker, final DOMRpcService rpc,
- final NetconfDeviceNotificationService notificationService) {
+ final DOMDataBroker broker, final DOMRpcService rpc,
+ final NetconfDeviceNotificationService newNotificationService) {
Preconditions.checkNotNull(mountService, "Closed");
Preconditions.checkState(topologyRegistration == null, "Already initialized");
mountBuilder.addService(DOMDataBroker.class, broker);
mountBuilder.addService(DOMRpcService.class, rpc);
- mountBuilder.addService(DOMNotificationService.class, notificationService);
- this.notificationService = notificationService;
+ mountBuilder.addService(DOMNotificationService.class, newNotificationService);
+ this.notificationService = newNotificationService;
topologyRegistration = mountBuilder.register();
LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
} else {
return new DefaultDOMRpcResult(input1.getErrors());
}
- });
+ }, MoreExecutors.directExecutor());
return Futures.makeChecked(transformed,
e -> new DOMRpcImplementationNotAvailableException(e,
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
- @Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T lsnr) {
throw new UnsupportedOperationException("Not available for netconf 1.0");
}
Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
"Submit failed with errors: %s", input.getErrors());
return null;
- });
+ }, MoreExecutors.directExecutor());
return Futures.makeChecked(commitFutureAsVoid, input -> new TransactionCommitFailedException(
"Submit of transaction " + getIdentifier() + " failed", input));
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
- (Function<RpcResult<TransactionStatus>, Void>) input -> null);
+ (Function<RpcResult<TransactionStatus>, Void>) input -> null, MoreExecutors.directExecutor());
return Futures.makeChecked(commmitFutureAsVoid,
input -> new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
netOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id));
}
- private static class Change {
+ private static final class Change {
private final DataContainerChild<?, ?> editStructure;
private final Optional<ModifyAction> defaultOperation;
- private Change(final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation) {
+ Change(final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation) {
this.editStructure = editStructure;
this.defaultOperation = defaultOperation;
}
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
-import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-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;
private static final Logger LOG = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class);
- private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
- "schemaDownload", SchemaSourceException.class) {
- @Override
- protected SchemaSourceException newWithCause(final String message, final Throwable throwable) {
- return new SchemaSourceException(message, throwable);
- }
- };
-
private final DOMRpcService rpc;
private final RemoteDeviceId id;
return Optional.absent();
}
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ final java.util.Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode,
}
@Override
- public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
- final SourceIdentifier sourceIdentifier) {
+ public ListenableFuture<YangTextSchemaSource> getSource(final SourceIdentifier sourceIdentifier) {
final String moduleName = sourceIdentifier.getName();
- // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
- final String badRev = sourceIdentifier.getRevision();
- final String formattedRevision = SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(badRev) ? null : badRev;
- final Optional<String> revision = Optional.fromNullable(formattedRevision);
+ final Optional<String> revision = Optional.fromJavaUtil(sourceIdentifier.getRevision().map(Revision::toString));
final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);
LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName,
revision);
- final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
- rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
- new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
-
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked =
- Futures.makeChecked(transformed, MAPPER);
-
- return checked;
+ return Futures.transform(
+ rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
+ new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision),
+ MoreExecutors.directExecutor());
}
/**
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
-import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
}
@Override
- public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
+ public ListenableFuture<? extends YangTextSchemaSource> getSource(
final SourceIdentifier sourceIdentifier) {
Preconditions.checkNotNull(sourceIdentifier);
Preconditions.checkArgument(availableSources.containsKey(sourceIdentifier));
return download(sourceIdentifier);
}
- private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(
- final SourceIdentifier sourceIdentifier) {
+ private ListenableFuture<? extends YangTextSchemaSource> download(final SourceIdentifier sourceIdentifier) {
final URL url = availableSources.get(sourceIdentifier);
try (InputStream in = url.openStream()) {
final String schemaContent = new String(ByteStreams.toByteArray(in));
new NetconfRemoteSchemaYangSourceProvider
.NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
- return Futures.immediateCheckedFuture(yangSource);
+ return Futures.immediateFuture(yangSource);
} catch (IOException e) {
LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e);
- return Futures.immediateFailedCheckedFuture(
- new SchemaSourceException(
- "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));
+ return Futures.immediateFailedFuture(new SchemaSourceException(
+ "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));
}
}
}
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
-import java.util.Comparator;
import java.util.Date;
import java.util.Map;
import javax.annotation.Nonnull;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.MessageCounter;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
private static NotificationDefinition getMostRecentNotification(
final Collection<NotificationDefinition> notificationDefinitions) {
- Comparator<NotificationDefinition> cmp = (o1, o2) ->
- o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
-
- return Collections.max(notificationDefinitions, cmp);
+ return Collections.max(notificationDefinitions, (o1, o2) ->
+ Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
}
@Override
// TODO maybe we should move this somewhere else as this
// might be used in applications using schemaless mountpoints
public static final YangInstanceIdentifier.NodeIdentifier SCHEMALESS_NOTIFICATION_PAYLOAD =
- new YangInstanceIdentifier.NodeIdentifier(QName.create("schemaless-notification-payload"));
+ // FIXME: assign proper namespace
+ new YangInstanceIdentifier.NodeIdentifier(QName.create("", "schemaless-notification-payload"));
private final MessageCounter counter;
public NetconfMessage toRpcRequest(final SchemaPath rpc, final NormalizedNode<?, ?> input) {
final DOMSource payload = (DOMSource) input.getValue();
wrapPayload((Document) payload.getNode());
- return new NetconfMessage(((Document) ((AnyXmlNode) input).getValue().getNode()));
+ return new NetconfMessage((Document) ((AnyXmlNode) input).getValue().getNode());
}
/**
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.FutureCallback;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.get.config.input.source.ConfigSource;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
this.rpc = rpc;
this.schemaContext = schemaContext;
- if ((rpc instanceof KeepaliveDOMRpcService)
- && (((KeepaliveDOMRpcService) rpc).getDeviceRpc() instanceof SchemalessNetconfDeviceRpc)) {
+ if (rpc instanceof KeepaliveDOMRpcService
+ && ((KeepaliveDOMRpcService) rpc).getDeviceRpc() instanceof SchemalessNetconfDeviceRpc) {
this.transformer = new SchemalessRpcStructureTransformer();
} else {
this.transformer = new NetconfRpcStructureTransformer(schemaContext);
private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(
final Optional<YangInstanceIdentifier> path, final ListenableFuture<DOMRpcResult> configRunning) {
- return Futures.transform(configRunning, (Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>) result -> {
+ return Futures.transform(configRunning, result -> {
Preconditions.checkArgument(
result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode =
((ContainerNode) result.getResult()).getChild(
NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
return transformer.selectFromDataStructure(dataNode, path.get());
- });
+ }, MoreExecutors.directExecutor());
}
public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback,
NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext)))
: rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
- Futures.addCallback(future, callback);
+ Futures.addCallback(future, callback, MoreExecutors.directExecutor());
return future;
}
public static DataContainerChild<?, ?> getSourceNode(final QName datastore) {
return Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_SOURCE_QNAME))
- .withChild(
- Builders.choiceBuilder().withNodeIdentifier(toId(ConfigSource.QNAME)).withChild(
- Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build()).build()
- ).build();
+ .withChild(Builders.choiceBuilder().withNodeIdentifier(toId(ConfigSource.QNAME)).withChild(
+ Builders.leafBuilder().withNodeIdentifier(toId(datastore)).withValue(Empty.getInstance()).build())
+ .build()).build();
}
public static ContainerNode getLockContent(final QName datastore) {
public static DataContainerChild<?, ?> getTargetNode(final QName datastore) {
return Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_TARGET_QNAME))
- .withChild(
- Builders.choiceBuilder().withNodeIdentifier(toId(ConfigTarget.QNAME)).withChild(
- Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build()).build()
- ).build();
+ .withChild(Builders.choiceBuilder().withNodeIdentifier(toId(ConfigTarget.QNAME)).withChild(
+ Builders.leafBuilder().withNodeIdentifier(toId(datastore)).withValue(Empty.getInstance()).build())
+ .build()).build();
}
public static NormalizedNode<?, ?> getCopyConfigContent(final QName source, final QName target) {
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-public class NetconfMessageTransformUtil {
+public final class NetconfMessageTransformUtil {
private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
} else {
final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
- configContent = ImmutableNodes
- .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
+ configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride.toJavaUtil(),
+ java.util.Optional.ofNullable(modifyOperation));
}
final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
notificationElement);
} catch (final DocumentedException e) {
- throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
+ throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
+ e);
} catch (final DateTimeParseException e) {
LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
NetconfNotification.UNKNOWN_EVENT_TIME, e);
public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
final YangInstanceIdentifier path) {
- return NormalizedNodes.findNode(data, path.getPathArguments());
+ return Optional.fromJavaUtil(NormalizedNodes.findNode(data, path.getPathArguments()));
}
@Override
public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
final YangInstanceIdentifier dataPath,
- Optional<ModifyAction> operation) {
+ final Optional<ModifyAction> operation) {
return NetconfMessageTransformUtil.createEditConfigAnyxml(schemaContext, dataPath, operation, data);
}
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
private final Map<QName, DataSchemaNode> childNodes;
private final QName qualifiedName;
- private final Set<AugmentationSchema> availableAugmentations;
+ private final Set<AugmentationSchemaNode> availableAugmentations;
public NodeContainerProxy(final QName qualifiedName, final Map<QName, DataSchemaNode> childNodes,
- final Set<AugmentationSchema> availableAugmentations) {
+ final Set<AugmentationSchemaNode> availableAugmentations) {
this.availableAugmentations = availableAugmentations;
this.childNodes = Preconditions.checkNotNull(childNodes, "childNodes");
this.qualifiedName = qualifiedName;
}
public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes) {
- this(qualifiedName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
+ this(qualifiedName, asMap(childNodes), Collections.emptySet());
}
public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes,
- final Set<AugmentationSchema> availableAugmentations) {
+ final Set<AugmentationSchemaNode> availableAugmentations) {
this(qualifiedName, asMap(childNodes), availableAugmentations);
}
}
@Override
- public DataSchemaNode getDataChildByName(final QName qualifiedName) {
- return childNodes.get(qualifiedName);
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
+ return Optional.ofNullable(childNodes.get(name));
}
@Override
}
@Override
- public Set<AugmentationSchema> getAvailableAugmentations() {
+ public Set<AugmentationSchemaNode> getAvailableAugmentations() {
return availableAugmentations;
}
throw new UnsupportedOperationException();
}
- @Override
- public ConstraintDefinition getConstraints() {
- throw new UnsupportedOperationException();
- }
-
@Override
public QName getQName() {
return qualifiedName;
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException();
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException();
}
public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return Collections.emptyList();
}
-}
\ No newline at end of file
+
+ @Override
+ public Set<NotificationDefinition> getNotifications() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Set<ActionDefinition> getActions() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Optional<RevisionAwareXPath> getWhenCondition() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ return Collections.emptySet();
+ }
+}
try {
textContent = key.get(0).getTextContent();
} catch (DocumentedException e) {
- throw new IllegalStateException("Key value not present in key element");
+ throw new IllegalStateException("Key value not present in key element", e);
}
if (!keyValues.get(qualifiedName).equals(textContent)) {
throw new IllegalStateException("Key value in path not equal to key value in xml");
final NetconfNode node = this.encryptPassword(input);
final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
final NodeId nodeId = new NodeId(input.getNodeId());
- writeToConfigDS(node, nodeId, topologyId, futureResult);
+ writeToConfigDS(node, nodeId, futureResult);
return futureResult;
}
return credentials;
}
- private void writeToConfigDS(final NetconfNode node, final NodeId nodeId, final String topologyId,
+ private void writeToConfigDS(final NetconfNode node, final NodeId nodeId,
final SettableFuture<RpcResult<Void>> futureResult) {
final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
Assert.assertThat(resolvedModulesSchema.size(), is(3));
Assert.assertTrue(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("module-with-revision",
- "2014-04-08")));
+ Revision.of("2014-04-08"))));
Assert.assertThat(resolvedModulesSchema.get(
- RevisionSourceIdentifier.create("module-with-revision", "2014-04-08")),
+ RevisionSourceIdentifier.create("module-with-revision", Revision.of("2014-04-08"))),
is(new URL("http://localhost:8181/yanglib/schemas/module-with-revision/2014-04-08")));
Assert.assertTrue(resolvedModulesSchema.containsKey(
- RevisionSourceIdentifier.create("another-module-with-revision", "2013-10-21")));
+ RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21"))));
Assert.assertThat(resolvedModulesSchema.get(
- RevisionSourceIdentifier.create("another-module-with-revision", "2013-10-21")),
+ RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21"))),
is(new URL("http://localhost:8181/yanglib/schemas/another-module-with-revision/2013-10-21")));
Assert.assertTrue(resolvedModulesSchema.containsKey(
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import com.google.common.base.Optional;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import java.io.IOException;
-import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
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.repo.spi.PotentialSchemaSource;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.xml.sax.SAXException;
public static final String TEST_MODULE = "test-module";
public static final String TEST_REVISION = "2013-07-22";
public static final SourceIdentifier TEST_SID =
- RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
+ RevisionSourceIdentifier.create(TEST_MODULE, Revision.of(TEST_REVISION));
public static final String TEST_CAPABILITY =
TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
public static final SourceIdentifier TEST_SID2 =
- RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
+ RevisionSourceIdentifier.create(TEST_MODULE + "2", Revision.of(TEST_REVISION));
public static final String TEST_CAPABILITY2 =
TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
doAnswer(invocation -> {
if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
- return Futures.immediateFailedCheckedFuture(schemaResolutionException);
+ return Futures.immediateFailedFuture(schemaResolutionException);
} else {
- return Futures.immediateCheckedFuture(schema);
+ return Futures.immediateFuture(schema);
}
}).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
final SchemaResolutionException schemaResolutionException
= new SchemaResolutionException("fail first",
Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
- doReturn(Futures.immediateFailedCheckedFuture(
- schemaResolutionException))
+ doReturn(Futures.immediateFailedFuture(schemaResolutionException))
.when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
// Make fallback attempt to fail due to empty resolved sources
final MissingSchemaSourceException schemaResolutionException =
new MissingSchemaSourceException("fail first", TEST_SID);
- doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException))
+ doReturn(Futures.immediateFailedFuture(schemaResolutionException))
.when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
doAnswer(invocation -> {
if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
- return Futures.immediateFailedCheckedFuture(schemaResolutionException);
+ return Futures.immediateFailedFuture(schemaResolutionException);
} else {
- return Futures.immediateCheckedFuture(schema);
+ return Futures.immediateFuture(schema);
}
}).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
private static SchemaRepository getSchemaRepository() {
final SchemaRepository mock = mock(SchemaRepository.class);
final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
- doReturn(Futures.immediateCheckedFuture(mockRep))
+ doReturn(Futures.immediateFuture(mockRep))
.when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
return mock;
}
final NetconfDeviceCommunicator listener = getListener();
final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
- doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail")))
- .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+ doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDeviceCommunicator listener = getListener();
final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
- doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail")))
- .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+ doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
= new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
private static SchemaContextFactory getSchemaFactory() throws Exception {
final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
- doReturn(Futures.immediateCheckedFuture(getSchema()))
+ doReturn(Futures.immediateFuture(getSchema()))
.when(schemaFactory).createSchemaContext(any(Collection.class));
return schemaFactory;
}
- public static SchemaContext getSchema() throws Exception {
- final List<InputStream> modelsToParse = Lists.newArrayList(
- NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
- );
- return YangParserTestUtils.parseYangStreams(modelsToParse);
+ public static SchemaContext getSchema() {
+ return YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
}
private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
Assert.assertTrue(availableYangSchemasQNames.isEmpty());
}
- @SuppressWarnings("checkstyle:IllegalThrows")
+ @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" })
@Test(expected = RuntimeException.class)
public void testCreateInterrupted() throws Throwable {
//NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread
import com.google.common.collect.Iterables;
import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
userNotification = new NetconfMessage(doc);
}
- static SchemaContext getNotificationSchemaContext(final Class<?> loadClass,
- final boolean getExceptionTest) throws Exception {
- final List<InputStream> modelsToParse = new ArrayList<>();
-
+ static SchemaContext getNotificationSchemaContext(final Class<?> loadClass, final boolean getExceptionTest) {
+ final SchemaContext context;
if (getExceptionTest) {
- modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification4.yang"));
- modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification3.yang"));
+ context = YangParserTestUtils.parseYangResources(loadClass, "/schemas/user-notification4.yang",
+ "/schemas/user-notification3.yang");
} else {
- modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification.yang"));
- modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification2.yang"));
+ context = YangParserTestUtils.parseYangResources(loadClass, "/schemas/user-notification.yang",
+ "/schemas/user-notification2.yang");
}
- final SchemaContext context = YangParserTestUtils.parseYangStreams(modelsToParse);
final Set<Module> modules = context.getModules();
assertTrue(!modules.isEmpty());
assertNotNull(context);
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
-import com.google.common.collect.Lists;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.List;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
static NetconfMessageTransformer messageTransformer;
@BeforeClass
- public static void setup() throws Exception {
- List<InputStream> modelsToParse = Collections.singletonList(
- NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
- final Set<Module> notifModules = YangParserTestUtils.parseYangStreams(modelsToParse).getModules();
+ public static void setup() {
+ final Set<Module> notifModules = YangParserTestUtils.parseYangResource(
+ "/schemas/rpc-notification-subscription.yang").getModules();
assertTrue(!notifModules.isEmpty());
- modelsToParse = Lists.newArrayList(
- NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/config-test-rpc.yang"),
- NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
- cfgCtx = YangParserTestUtils.parseYangStreams(modelsToParse);
+ cfgCtx = YangParserTestUtils.parseYangResources(NetconfToRpcRequestTest.class,
+ "/schemas/config-test-rpc.yang", "/schemas/rpc-notification-subscription.yang");
messageTransformer = new NetconfMessageTransformer(cfgCtx, true);
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
doReturn(mockChannelFuture).when(mockChannelFuture)
- .addListener(any((GenericFutureListener.class)));
+ .addListener(any(GenericFutureListener.class));
doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
ListenableFuture<RpcResult<NetconfMessage>> resultFuture =
- communicator.sendRequest(message, QName.create("mock rpc"));
+ communicator.sendRequest(message, QName.create("", "mockRpc"));
if (doLastTest) {
assertNotNull("ListenableFuture is null", resultFuture);
}
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create("mock rpc");
+ QName rpc = QName.create("", "mockRpc");
ArgumentCaptor<GenericFutureListener> futureListener =
ArgumentCaptor.forClass(GenericFutureListener.class);
@Test
public void testSendRequestWithNoSession() throws Exception {
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create("mock rpc");
+ QName rpc = QName.create("", "mockRpc");
ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create("mock rpc");
+ QName rpc = QName.create("", "mockRpc");
ArgumentCaptor<GenericFutureListener> futureListener =
ArgumentCaptor.forClass(GenericFutureListener.class);
String errorInfo = rpcError.getInfo();
assertNotNull("RpcError info is null", errorInfo);
- assertEquals("Error info contains \"foo\"", true,
- errorInfo.contains("<bad-attribute>foo</bad-attribute>"));
- assertEquals("Error info contains \"bar\"", true,
- errorInfo.contains("<bad-element>bar</bad-element>"));
+ assertTrue("Error info contains \"foo\"", errorInfo.contains("<bad-attribute>foo</bad-attribute>"));
+ assertTrue("Error info contains \"bar\"", errorInfo.contains("<bad-element>bar</bad-element>"));
}
/**
RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.PROTOCOL,
"bad-attribute");
- assertEquals("RpcError message non-empty", true,
- !Strings.isNullOrEmpty(rpcError.getMessage()));
+ assertFalse("RpcError message non-empty", Strings.isNullOrEmpty(rpcError.getMessage()));
String errorInfo = rpcError.getInfo();
assertNotNull("RpcError info is null", errorInfo);
- assertEquals("Error info contains \"actual-message-id\"", true,
- errorInfo.contains("actual-message-id"));
- assertEquals("Error info contains \"expected-message-id\"", true,
- errorInfo.contains("expected-message-id"));
+ assertTrue("Error info contains \"actual-message-id\"", errorInfo.contains("actual-message-id"));
+ assertTrue("Error info contains \"expected-message-id\"", errorInfo.contains("expected-message-id"));
}
@Test
private static void verifyResponseMessage(final RpcResult<NetconfMessage> rpcResult, final String dataText) {
assertNotNull("RpcResult is null", rpcResult);
- assertEquals("isSuccessful", true, rpcResult.isSuccessful());
+ assertTrue("isSuccessful", rpcResult.isSuccessful());
NetconfMessage messageResult = rpcResult.getResult();
assertNotNull("getResult", messageResult);
// List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
private static RpcError verifyErrorRpcResult(final RpcResult<NetconfMessage> rpcResult,
final RpcError.ErrorType expErrorType, final String expErrorTag) {
assertNotNull("RpcResult is null", rpcResult);
- assertEquals("isSuccessful", false, rpcResult.isSuccessful());
+ assertFalse("isSuccessful", rpcResult.isSuccessful());
assertNotNull("RpcResult errors is null", rpcResult.getErrors());
assertEquals("Errors size", 1, rpcResult.getErrors().size());
RpcError rpcError = rpcResult.getErrors().iterator().next();
final String msg = rpcError.getMessage();
assertNotNull("getMessage is null", msg);
assertFalse("getMessage is empty", msg.isEmpty());
- assertFalse("getMessage is blank", CharMatcher.WHITESPACE.matchesAllOf(msg));
+ assertFalse("getMessage is blank", CharMatcher.whitespace().matchesAllOf(msg));
return rpcError;
}
}
doReturn(Futures.immediateCheckedFuture(result))
.when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final KeepaliveSalFacade keepaliveSalFacade =
- new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L);
- keepaliveSalFacade.setListener(listener);
-
keepaliveSalFacade.onDeviceConnected(null, null, deviceRpc);
verify(underlyingSalFacade).onDeviceConnected(
doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state")))
.when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final KeepaliveSalFacade keepaliveSalFacade =
- new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L);
- keepaliveSalFacade.setListener(listener);
-
keepaliveSalFacade.onDeviceConnected(null, null, deviceRpc);
verify(underlyingSalFacade).onDeviceConnected(
doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state")))
.when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final KeepaliveSalFacade keepaliveSalFacade =
+ keepaliveSalFacade =
new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 100L, 1L);
keepaliveSalFacade.setListener(listener);
verify(listener, times(1)).disconnect();
}
-}
\ No newline at end of file
+}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- final SchemaPath path1 = SchemaPath.create(true, new QName(new URI("namespace1"), "path1"));
- final SchemaPath path2 = SchemaPath.create(true, new QName(new URI("namespace2"), "path2"));
+ final SchemaPath path1 = SchemaPath.create(true, QName.create(new URI("namespace1"), "path1"));
+ final SchemaPath path2 = SchemaPath.create(true, QName.create(new URI("namespace2"), "path2"));
service = new NetconfDeviceNotificationService();
service.registerNotificationListener(listener1, path1);
registration = service.registerNotificationListener(listener2, path2);
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
-import java.io.InputStream;
import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.EnumMap;
-import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javassist.ClassPool;
public class NetconfDeviceTopologyAdapterTest {
- private RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
+ private final RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
@Mock
private DataBroker broker;
@Mock
private NetconfNode data;
- private String txIdent = "test transaction";
+ private final String txIdent = "test transaction";
private SchemaContext schemaContext = null;
- private String sessionIdForReporting = "netconf-test-session1";
+ private final String sessionIdForReporting = "netconf-test-session1";
private BindingTransactionChain transactionChain;
doReturn(txIdent).when(writeTx).getIdentifier();
- this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
+ this.schemaContext = YangParserTestUtils.parseYangResources(NetconfDeviceTopologyAdapterTest.class,
+ "/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang",
+ "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang",
+ "/schemas/network-topology-augment-test@2016-08-08.yang");
schemaContext.getModules();
final SchemaService schemaService = createSchemaService();
datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
- 16, 16, "CommitFutures");
+ 16, 16, "CommitFutures", NetconfDeviceTopologyAdapterTest.class);
concurrentDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction,
- Throwable cause) {
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
}
@Override
- public void onTransactionChainSuccessful(TransactionChain<?, ?> chain) {
+ public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
}
});
NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId)
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build();
- DOMDataWriteTransaction writeTx = concurrentDOMDataBroker.newWriteOnlyTransaction();
- writeTx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
- writeTx.submit();
+ DOMDataWriteTransaction wtx = concurrentDOMDataBroker.newWriteOnlyTransaction();
+ wtx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
+ wtx.submit();
adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
Optional<NormalizedNode<?, ?>> testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
dataTestId, testNode.get().getValue());
}
- private List<InputStream> getYangSchemas() {
- final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
- "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
- "/schemas/netconf-node-topology.yang", "/schemas/network-topology-augment-test@2016-08-08.yang");
- final List<InputStream> schemas = new ArrayList<>();
-
- for (String schemaPath : schemaPaths) {
- InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
- schemas.add(resourceAsStream);
- }
-
- return schemas;
- }
-
private SchemaService createSchemaService() {
return new SchemaService() {
@Override
- public void addModule(Module module) {
+ public void addModule(final Module module) {
}
@Override
- public void removeModule(Module module) {
+ public void removeModule(final Module module) {
}
@Test
public void testChainFail() throws Exception {
final AbstractWriteTx writeTx = chain.newWriteOnlyTransaction();
- final ArgumentCaptor<TxListener> captor = ArgumentCaptor.forClass(TxListener.class);
verify(writeOnlyTx1).addListener(captor.capture());
writeTx.submit();
final TransactionCommitFailedException cause = new TransactionCommitFailedException("fail");
// 1 transaction failed, onTransactionChainSuccessful must not be called
verify(listener, never()).onTransactionChainSuccessful(chain);
}
-}
\ No newline at end of file
+}
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-class TxTestUtils {
+final class TxTestUtils {
private static final QName Q_NAME_1 = QName.create("test:namespace", "2013-07-22", "c");
private static final QName Q_NAME_2 = QName.create(Q_NAME_1, "a");
+ private TxTestUtils() {
+
+ }
+
static YangInstanceIdentifier getContainerId() {
return YangInstanceIdentifier.builder()
.node(Q_NAME_1)
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any());
netconfOps = new NetconfBaseOps(rpc, schemaContext);
id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830));
}
private static ContainerNode getLockContent(final QName op, final QName datastore) {
- final LeafNode<Object> datastoreLeaf = Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build();
+ final LeafNode<Object> datastoreLeaf = Builders.leafBuilder().withNodeIdentifier(toId(datastore))
+ .withValue(Empty.getInstance()).build();
final ChoiceNode choice = Builders.choiceBuilder()
.withNodeIdentifier(toId(ConfigTarget.QNAME))
.withChild(datastoreLeaf)
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any());
netconfOps = new NetconfBaseOps(rpc, schemaContext);
id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830));
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any());
netconfOps = new NetconfBaseOps(rpc, schemaContext);
id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830));
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
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.impl.schema.builder.impl.ImmutableAnyXmlNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
+import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.w3c.dom.Document;
@Test
public void testGetSource() throws Exception {
- final SourceIdentifier identifier = SourceIdentifier.create("test", Optional.of("2016-02-08"));
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> module = provider.getSource(identifier);
- final YangTextSchemaSource source = module.checkedGet();
+ final SourceIdentifier identifier = RevisionSourceIdentifier.create("test", Revision.of("2016-02-08"));
+ final YangTextSchemaSource source = provider.getSource(identifier).get();
Assert.assertEquals(identifier, source.getIdentifier());
verify(service).invokeRpc(
SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
- NetconfRemoteSchemaYangSourceProvider
- .createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision()))
+ NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest(identifier.getName(),
+ Optional.fromJavaUtil(identifier.getRevision().map(Revision::toString)))
);
}
*/
package org.opendaylight.netconf.sal.connect.netconf.schema;
-import com.google.common.base.Optional;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import com.google.common.io.ByteStreams;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
@Before
public void setUp() throws Exception {
final URL url = getClass().getResource("/schemas/config-test-rpc.yang");
- workingSid = RevisionSourceIdentifier.create("abc", Optional.<String>absent());
+ workingSid = RevisionSourceIdentifier.create("abc", Optional.empty());
final Map<SourceIdentifier, URL> sourceIdentifierURLMap = Collections.singletonMap(workingSid, url);
final RemoteDeviceId id = new RemoteDeviceId("id", new InetSocketAddress("localhost", 22));
yangLibrarySchemaYangSourceProvider = new YangLibrarySchemaYangSourceProvider(id, sourceIdentifierURLMap);
@Test
public void testGetSource() throws Exception {
- CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source =
- yangLibrarySchemaYangSourceProvider.getSource(workingSid);
- final String x = new String(ByteStreams.toByteArray(source.checkedGet().openStream()));
+ ListenableFuture<? extends YangTextSchemaSource> source = yangLibrarySchemaYangSourceProvider
+ .getSource(workingSid);
+ final String x = new String(ByteStreams.toByteArray(source.get().openStream()));
Assert.assertThat(x, CoreMatchers.containsString("module config-test-rpc"));
}
- @Test(expected = SchemaSourceException.class)
- public void testGetSourceFailure() throws Exception {
+ @Test
+ public void testGetSourceFailure() throws InterruptedException, MalformedURLException {
final URL url = new URL("http://non-existing-entity.yang");
final Map<SourceIdentifier, URL> sourceIdentifierURLMap = Collections.singletonMap(workingSid, url);
final RemoteDeviceId id = new RemoteDeviceId("id", new InetSocketAddress("localhost", 22));
final YangLibrarySchemaYangSourceProvider failingYangLibrarySchemaYangSourceProvider =
new YangLibrarySchemaYangSourceProvider(id, sourceIdentifierURLMap);
- CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source =
- failingYangLibrarySchemaYangSourceProvider.getSource(workingSid);
- source.checkedGet();
+ try {
+ failingYangLibrarySchemaYangSourceProvider.getSource(workingSid).get();
+ fail();
+ } catch (ExecutionException e) {
+ final Throwable cause = e.getCause();
+ assertTrue(cause instanceof SchemaSourceException);
+ }
}
@Test(expected = IllegalArgumentException.class)
package org.opendaylight.netconf.sal.connect.netconf.schema.mapping;
-import com.google.common.base.Optional;
import java.io.InputStream;
+import java.util.Optional;
import javax.xml.transform.dom.DOMSource;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.target.config.target.Candidate;
+import org.opendaylight.yangtools.yang.common.Empty;
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.ChoiceNode;
final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
.withChild(Builders.leafBuilder().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
+ new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME))
+ .withValue(Empty.getInstance()).build())
.build();
final DataContainerChild<?, ?> target = Builders.containerBuilder()
.withNodeIdentifier(
Assert.assertNotNull(result.getResult());
final ContainerNode rpcReply = (ContainerNode) result.getResult();
Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME, rpcReply.getNodeType());
- final Optional dataOpt = rpcReply.getChild(
+ final Optional<?> dataOpt = rpcReply.getChild(
new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
Assert.assertTrue(dataOpt.isPresent());
final AnyXmlNode data = (AnyXmlNode) dataOpt.get();
@Test
public void tesGetSchemaResponse() throws Exception {
- final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
+ final NetconfMessageTransformer transformer = getTransformer(getSchema(true));
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
"<rpc-reply message-id=\"101\"\n"
+ "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ "</data>\n"
+ "</rpc-reply>"
));
- final DOMRpcResult compositeNodeRpcResult =
- netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
+ final DOMRpcResult compositeNodeRpcResult = transformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
final DOMSource schemaContent =
+ "</data>\n"
+ "</rpc-reply>"));
- final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
+ final NetconfMessageTransformer transformer = getTransformer(getSchema(true));
final DOMRpcResult compositeNodeRpcResult =
- netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
+ transformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME)))
.thenReturn(RpcResultBuilder.success(ok).buildFuture());
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
final MessageTransformer<NetconfMessage> transformer = new NetconfMessageTransformer(schemaContext, true);
final DOMRpcService rpc = new NetconfDeviceRpc(schemaContext, listener, transformer);
final RemoteDeviceId id =
private final Document expected;
- private NetconfMessageMatcher(final Document expected) {
+ NetconfMessageMatcher(final Document expected) {
this.expected = removeAttrs(expected);
}
}
}
-}
\ No newline at end of file
+}
assertEquals(TEST_PWD, loginPw.getLoginPasswordUnencrypted().getPassword());
}
- private CreateDeviceInput getInput(boolean encrypt) {
+ private static CreateDeviceInput getInput(final boolean encrypt) {
CreateDeviceInputBuilder builder = new CreateDeviceInputBuilder();
final Credentials credentials;
if (encrypt) {
builder.setCredentials(credentials);
builder.setHost(new Host(new IpAddress(new Ipv4Address("10.18.16.188"))));
builder.setPort(new PortNumber(830));
- builder.setTcpOnly(false);
+ builder.setTcpOnly(Boolean.FALSE);
builder.setNodeId(NODE_ID.toString());
return builder.build();
}
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
public class NodeContainerProxyTest {
private static final QName NODE_1_QNAME = QName.create(QNAME, "node-1");
private static final QName NODE_2_QNAME = QName.create(QNAME, "node-2");
@Mock
- private AugmentationSchema augSchema1;
+ private AugmentationSchemaNode augSchema1;
@Mock
- private AugmentationSchema augSchema2;
+ private AugmentationSchemaNode augSchema2;
@Mock
private DataSchemaNode schemaNode1;
@Mock
final Map<QName, DataSchemaNode> childNodes = new HashMap<>();
childNodes.put(NODE_1_QNAME, schemaNode1);
childNodes.put(NODE_2_QNAME, schemaNode2);
- final Set<AugmentationSchema> augmentations = new HashSet<>();
+ final Set<AugmentationSchemaNode> augmentations = new HashSet<>();
augmentations.add(augSchema1);
augmentations.add(augSchema2);
proxy = new NodeContainerProxy(QNAME, childNodes, augmentations);
@Test
public void testGetAvailableAugmentations() throws Exception {
- final Set<AugmentationSchema> augmentations = proxy.getAvailableAugmentations();
+ final Set<AugmentationSchemaNode> augmentations = proxy.getAvailableAugmentations();
Assert.assertEquals(2, augmentations.size());
Assert.assertTrue(augmentations.contains(augSchema1));
Assert.assertTrue(augmentations.contains(augSchema2));
proxy.isConfiguration();
}
- @Test(expected = UnsupportedOperationException.class)
- public void testGetConstraints() throws Exception {
- proxy.getConstraints();
- }
-
@Test(expected = UnsupportedOperationException.class)
public void testGetPath() throws Exception {
proxy.getPath();
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public final class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
+ private Main() {
+
+ }
+
@SuppressWarnings("checkstyle:IllegalCatch")
public static void main(final String[] args) {
final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
private final Set<Capability> caps;
private final SchemaContext schemaContext;
- private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
+ private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
MdsalOperationProvider(final SessionIdProvider idProvider,
final Set<Capability> caps,
@Override
public AutoCloseable registerCapabilityListener(
- CapabilityListener listener) {
+ final CapabilityListener listener) {
listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- }
+ return () -> {
};
}
@Override
- public NetconfOperationService createService(String netconfSessionIdForReporting) {
+ public NetconfOperationService createService(final String netconfSessionIdForReporting) {
return new MdsalOperationService(Long.parseLong(netconfSessionIdForReporting), schemaContext,
caps, sourceProvider);
}
private final Set<Capability> caps;
private final SchemaService schemaService;
private final DOMDataBroker dataBroker;
- private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
+ private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
MdsalOperationService(final long currentSessionId,
final SchemaContext schemaContext,
ContainerNode schemasContainer = Builders.containerBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(Schemas.QNAME)).withChild(schemaList).build();
- return (ContainerNode) Builders.containerBuilder().withNodeIdentifier(
+ return Builders.containerBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(NetconfState.QNAME)).withChild(schemasContainer).build();
}
- private DOMDataBroker createDataStore(SchemaService schemaService, long sessionId) {
+ private static DOMDataBroker createDataStore(final SchemaService schemaService, final long sessionId) {
LOG.debug("Session {}: Creating data stores for simulated device", sessionId);
final DOMStore operStore = InMemoryDOMDataStoreFactory
.create("DOM-OPER", schemaService);
.create("DOM-CFG", schemaService);
ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
- 16, 16, "CommitFutures");
+ 16, 16, "CommitFutures", MdsalOperationProvider.class);
final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
return new SchemaService() {
@Override
- public void addModule(Module module) {
+ public void addModule(final Module module) {
}
@Override
- public void removeModule(Module module) {
+ public void removeModule(final Module module) {
}
package org.opendaylight.netconf.test.tool;
-import com.google.common.base.MoreObjects;
+import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.channel.Channel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
-import org.apache.sshd.common.util.ThreadUtils;
-import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.common.keyprovider.KeyPairProvider;
+import org.apache.sshd.common.util.security.SecurityUtils;
+import org.apache.sshd.common.util.threads.ThreadUtils;
import org.opendaylight.controller.config.util.capability.BasicCapability;
import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.config.util.capability.YangModuleCapability;
import org.opendaylight.netconf.test.tool.operations.OperationsProvider;
import org.opendaylight.netconf.test.tool.rpchandler.SettableOperationRpcProvider;
import org.opendaylight.netconf.test.tool.schemacache.SchemaSourceCache;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private boolean sendFakeSchema = false;
- public NetconfDeviceSimulator(Configuration configuration) {
+ public NetconfDeviceSimulator(final Configuration configuration) {
this.configuration = configuration;
this.nettyThreadgroup = new NioEventLoopGroup();
this.hashedWheelTimer = new HashedWheelTimer();
final List<Integer> openDevices = Lists.newArrayList();
// Generate key to temp folder
- final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
+ final KeyPairProvider keyPairProvider = getPemGeneratorHostKeyProvider();
for (int i = 0; i < configuration.getDeviceCount(); i++) {
if (currentPort > 65535) {
}
private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
- final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
+ final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) throws IOException {
return new SshProxyServerConfigurationBuilder()
.setBindingAddress(bindingAddress)
.setLocalAddress(tcpLocalAddress)
.createSshProxyServerConfiguration();
}
- private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
+ private static KeyPairProvider getPemGeneratorHostKeyProvider() {
try {
final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
- return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString(), "RSA", 4096);
+ return SecurityUtils.createGeneratorHostKeyProvider(tempFile.toAbsolutePath());
} catch (final IOException e) {
LOG.error("Unable to generate PEM key", e);
throw new RuntimeException(e);
}
configuration.getDefaultYangResources().forEach(r -> {
- SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(), r.getRevision());
+ SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(),
+ Revision.ofNullable(r.getRevision()));
registerSource(consumer, r.getResourcePath(), sourceIdentifier);
});
try {
//necessary for creating mdsal data stores and operations
- this.schemaContext = consumer.createSchemaContextFactory(
- SchemaSourceFilter.ALWAYS_ACCEPT)
- .createSchemaContext(loadedSources).checkedGet();
- } catch (final SchemaResolutionException e) {
+ this.schemaContext = consumer.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT)
+ .createSchemaContext(loadedSources).get();
+ } catch (final InterruptedException | ExecutionException e) {
throw new RuntimeException("Cannot parse schema context", e);
}
return capabilities;
}
- private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
+ private static void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
final Module module) {
- final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
- (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() :
- Optional.of(module.getQNameModule().getFormattedRevision())));
+ final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(),
+ module.getRevision());
try {
final String moduleContent = new String(
- consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).checkedGet().read());
+ consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).get().read());
capabilities.add(new YangModuleCapability(module, moduleContent));
//IOException would be thrown in creating SchemaContext already
- } catch (SchemaSourceException | IOException e) {
+ } catch (ExecutionException | InterruptedException | IOException e) {
throw new RuntimeException("Cannot retrieve schema source for module "
+ moduleSourceIdentifier.toString() + " from schema repository", e);
}
}
- private void registerSource(final SharedSchemaRepository consumer, final String resource,
+ private static void registerSource(final SharedSchemaRepository consumer, final String resource,
final SourceIdentifier sourceId) {
- consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
+ consumer.registerSchemaSource(sourceIdentifier -> Futures.immediateFuture(new YangTextSchemaSource(sourceId) {
@Override
- public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(
- final SourceIdentifier sourceIdentifier) {
- return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
- @Override
- protected MoreObjects.ToStringHelper addToStringAttributes(
- final MoreObjects.ToStringHelper toStringHelper) {
- return toStringHelper;
- }
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+ return toStringHelper;
+ }
- @Override
- public InputStream openStream() throws IOException {
- return getClass().getResourceAsStream(resource);
- }
- });
+ @Override
+ public InputStream openStream() throws IOException {
+ return getClass().getResourceAsStream(resource);
}
- }, PotentialSchemaSource.create(
- sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
+ }), PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
+ PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
}
private static InetSocketAddress getAddress(final String ip, final int port) {
@Override
public void close() {
for (final SshProxyServer sshWrapper : sshWrappers) {
- sshWrapper.close();
+ try {
+ sshWrapper.close();
+ } catch (IOException e) {
+ LOG.debug("Wrapper {} failed to close", sshWrapper, e);
+ }
}
for (final Channel deviceCh : devicesChannels) {
deviceCh.close();
import java.io.InputStream;
public final class TestToolUtils {
+ private TestToolUtils() {
+
+ }
public static String getMac(long mac) {
final StringBuilder builder = new StringBuilder(Long.toString(mac, 16));
editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
}
} catch (final IOException e) {
- throw new IllegalArgumentException("Cannot read content of " + editContent);
+ throw new IllegalArgumentException("Cannot read content of " + editContent, e);
}
int from;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RestPerfClient {
+public final class RestPerfClient {
private static final Logger LOG = LoggerFactory.getLogger(RestPerfClient.class);
}
}
+ private RestPerfClient() {
+
+ }
+
public static void main(String[] args) throws IOException {
Parameters parameters = parseArgs(args, Parameters.getParser());
try {
editContentString = Files.toString(parameters.editContent, StandardCharsets.UTF_8);
} catch (final IOException e) {
- throw new IllegalArgumentException("Cannot read content of " + parameters.editContent);
+ throw new IllegalArgumentException("Cannot read content of " + parameters.editContent, e);
}
final int threadAmount = parameters.threadAmount;
import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory;
import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
-public class ConfigurableClientDispatcher extends NetconfClientDispatcherImpl {
+public final class ConfigurableClientDispatcher extends NetconfClientDispatcherImpl {
private final Set<String> capabilities;
private static Parameters params;
+ private StressClient() {
+
+ }
+
public static void main(final String[] args) {
params = parseArgs(args, Parameters.getParser());
try {
editContentString = Files.toString(params.editContent, StandardCharsets.UTF_8);
} catch (final IOException e) {
- throw new IllegalArgumentException("Cannot read content of " + params.editContent);
+ throw new IllegalArgumentException("Cannot read content of " + params.editContent, e);
}
for (int i = 0; i < threadAmount; i++) {
final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
final Timer timer = new HashedWheelTimer();
- final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
+ final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(nioGroup, timer);
final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
for (final List<NetconfMessage> messages : allPreparedMessages) {
return netconfMessage;
}
- private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params,
- final NioEventLoopGroup nioGroup, final Timer timer) {
+ private static NetconfClientDispatcherImpl configureClientDispatcher(final NioEventLoopGroup nioGroup,
+ final Timer timer) {
final NetconfClientDispatcherImpl netconfClientDispatcher;
if (params.exi) {
if (params.legacyFraming) {
import java.security.PublicKey;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-
-import org.apache.sshd.server.PublickeyAuthenticator;
+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;
"/META-INF/yang/ietf-inet-types@2013-07-15.yang")
);
- public static final AuthProvider DEFAULT_AUTH_PROVIDER = new AuthProvider() {
- @Override
- public boolean authenticated(String username, String password) {
- LOG.info("Auth with username and password: {}", username);
- return true;
- }
+ public static final AuthProvider DEFAULT_AUTH_PROVIDER = (username, password) -> {
+ LOG.info("Auth with username and password: {}", username);
+ return true;
};
public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = new PublickeyAuthenticator() {
@Override
- public boolean authenticate(String username, PublicKey key, ServerSession session) {
+ public boolean authenticate(final String username, final PublicKey key, final ServerSession session) {
LOG.info("Auth with public key: {}", key);
return true;
}
return publickeyAuthenticator;
}
- public void setPublickeyAuthenticator(PublickeyAuthenticator publickeyAuthenticator) {
+ public void setPublickeyAuthenticator(final PublickeyAuthenticator publickeyAuthenticator) {
this.publickeyAuthenticator = publickeyAuthenticator;
}
return authProvider;
}
- public void setAuthProvider(AuthProvider authProvider) {
+ public void setAuthProvider(final AuthProvider authProvider) {
this.authProvider = authProvider;
}
return defaultYangResources;
}
- public void setDefaultYangResources(Set<YangResource> defaultYangResources) {
+ public void setDefaultYangResources(final Set<YangResource> defaultYangResources) {
this.defaultYangResources = defaultYangResources;
}
return threadPoolSize;
}
- public void setThreadPoolSize(int threadPoolSize) {
+ public void setThreadPoolSize(final int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
return startingPort;
}
- public void setStartingPort(int startingPort) {
+ public void setStartingPort(final int startingPort) {
this.startingPort = startingPort;
}
return deviceCount;
}
- public void setDeviceCount(int deviceCount) {
+ public void setDeviceCount(final int deviceCount) {
this.deviceCount = deviceCount;
}
return generateConfigsTimeout;
}
- public void setGenerateConfigsTimeout(int generateConfigsTimeout) {
+ public void setGenerateConfigsTimeout(final int generateConfigsTimeout) {
this.generateConfigsTimeout = generateConfigsTimeout;
}
return ssh;
}
- public void setSsh(boolean ssh) {
+ public void setSsh(final boolean ssh) {
this.ssh = ssh;
}
return ip;
}
- public void setIp(String ip) {
+ public void setIp(final String ip) {
this.ip = ip;
}
return models;
}
- public void setModels(Set<String> models) {
+ public void setModels(final Set<String> models) {
this.models = models;
}
return capabilities;
}
- public void setCapabilities(Set<String> capabilities) {
+ public void setCapabilities(final Set<String> capabilities) {
this.capabilities = capabilities;
}
return rpcHandler;
}
- public void setRpcHandler(RpcHandler rpcHandler) {
+ public void setRpcHandler(final RpcHandler rpcHandler) {
this.rpcHandler = rpcHandler;
}
return operationsCreator;
}
- public void setOperationsCreator(OperationsCreator operationsCreator) {
+ public void setOperationsCreator(final OperationsCreator operationsCreator) {
this.operationsCreator = operationsCreator;
}
}
@Deprecated
- public void setMdSal(boolean mdSal) {
+ public void setMdSal(final boolean mdSal) {
this.mdSal = mdSal;
}
}
@Deprecated
- public void setRpcConfigFile(File rpcConfigFile) {
+ public void setRpcConfigFile(final File rpcConfigFile) {
this.rpcConfigFile = rpcConfigFile;
}
}
@Deprecated
- public void setNotificationFile(File notificationFile) {
+ public void setNotificationFile(final File notificationFile) {
this.notificationFile = notificationFile;
}
}
@Deprecated
- public void setInitialConfigXMLFile(File initialConfigXMLFile) {
+ public void setInitialConfigXMLFile(final File initialConfigXMLFile) {
this.initialConfigXMLFile = initialConfigXMLFile;
}
}
@Deprecated
- public void setSchemasDir(File schemasDir) {
+ public void setSchemasDir(final File schemasDir) {
this.schemasDir = schemasDir;
}
}
import java.io.File;
import java.util.Set;
-
-import org.apache.sshd.server.PublickeyAuthenticator;
+import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.opendaylight.netconf.auth.AuthProvider;
import org.opendaylight.netconf.test.tool.TesttoolParameters;
import org.opendaylight.netconf.test.tool.operations.OperationsCreator;
public class ConfigurationBuilder {
- private Configuration configuration;
+ private final Configuration configuration;
public ConfigurationBuilder() {
this.configuration = new Configuration();
}
- public ConfigurationBuilder setPublickeyAuthenticator(PublickeyAuthenticator publickeyAuthenticator) {
+ public ConfigurationBuilder setPublickeyAuthenticator(final PublickeyAuthenticator publickeyAuthenticator) {
this.configuration.setPublickeyAuthenticator(publickeyAuthenticator);
return this;
}
- public ConfigurationBuilder setAuthProvider(AuthProvider authProvider) {
+ public ConfigurationBuilder setAuthProvider(final AuthProvider authProvider) {
this.configuration.setAuthProvider(authProvider);
return this;
}
- public ConfigurationBuilder setGetDefaultYangResources(Set<YangResource> defaultYangResources) {
+ public ConfigurationBuilder setGetDefaultYangResources(final Set<YangResource> defaultYangResources) {
this.configuration.setDefaultYangResources(defaultYangResources);
return this;
}
- public ConfigurationBuilder setThreadPoolSize(int threadPoolSize) {
+ public ConfigurationBuilder setThreadPoolSize(final int threadPoolSize) {
this.configuration.setThreadPoolSize(threadPoolSize);
return this;
}
- public ConfigurationBuilder setGenerateConfigsTimeout(int generateConfigsTimeout) {
+ public ConfigurationBuilder setGenerateConfigsTimeout(final int generateConfigsTimeout) {
this.configuration.setGenerateConfigsTimeout(generateConfigsTimeout);
return this;
}
- public ConfigurationBuilder setModels(Set<String> models) {
+ public ConfigurationBuilder setModels(final Set<String> models) {
this.configuration.setModels(models);
return this;
}
- public ConfigurationBuilder setCapabilities(Set<String> capabilities) {
+ public ConfigurationBuilder setCapabilities(final Set<String> capabilities) {
this.configuration.setCapabilities(capabilities);
return this;
}
- public ConfigurationBuilder setStartingPort(int startingPort) {
+ public ConfigurationBuilder setStartingPort(final int startingPort) {
this.configuration.setStartingPort(startingPort);
return this;
}
- public ConfigurationBuilder setDeviceCount(int deviceCount) {
+ public ConfigurationBuilder setDeviceCount(final int deviceCount) {
this.configuration.setDeviceCount(deviceCount);
return this;
}
- public ConfigurationBuilder setSsh(boolean ssh) {
+ public ConfigurationBuilder setSsh(final boolean ssh) {
this.configuration.setSsh(ssh);
return this;
}
- public ConfigurationBuilder setIp(String ip) {
+ public ConfigurationBuilder setIp(final String ip) {
this.configuration.setIp(ip);
return this;
}
- public ConfigurationBuilder setRpcMapping(RpcHandler rpcHandler) {
+ public ConfigurationBuilder setRpcMapping(final RpcHandler rpcHandler) {
this.configuration.setRpcHandler(rpcHandler);
return this;
}
@Deprecated
- public ConfigurationBuilder setMdSal(boolean mdSal) {
+ public ConfigurationBuilder setMdSal(final boolean mdSal) {
this.configuration.setMdSal(mdSal);
return this;
}
@Deprecated
- public ConfigurationBuilder setRpcConfigFile(File rpcConfigFile) {
+ public ConfigurationBuilder setRpcConfigFile(final File rpcConfigFile) {
this.configuration.setRpcConfigFile(rpcConfigFile);
return this;
}
@Deprecated
- public ConfigurationBuilder setInitialConfigXMLFile(File initialConfigXMLFile) {
+ public ConfigurationBuilder setInitialConfigXMLFile(final File initialConfigXMLFile) {
this.configuration.setInitialConfigXMLFile(initialConfigXMLFile);
return this;
}
@Deprecated
- public ConfigurationBuilder setNotificationFile(File notificationFile) {
+ public ConfigurationBuilder setNotificationFile(final File notificationFile) {
this.configuration.setNotificationFile(notificationFile);
return this;
}
- public ConfigurationBuilder setOperationsCreator(OperationsCreator operationsCreator) {
+ public ConfigurationBuilder setOperationsCreator(final OperationsCreator operationsCreator) {
this.configuration.setOperationsCreator(operationsCreator);
return this;
}
- public ConfigurationBuilder from(Configuration configuration) {
- this.configuration.setThreadPoolSize(configuration.getThreadPoolSize());
- this.configuration.setGenerateConfigsTimeout(configuration.getGenerateConfigsTimeout());
- this.configuration.setModels(configuration.getModels());
- this.configuration.setCapabilities(configuration.getCapabilities());
- this.configuration.setStartingPort(configuration.getStartingPort());
- this.configuration.setDeviceCount(configuration.getDeviceCount());
- this.configuration.setSsh(configuration.isSsh());
- this.configuration.setIp(configuration.getIp());
- this.configuration.setRpcHandler(configuration.getRpcHandler());
- this.configuration.setOperationsCreator(configuration.getOperationsCreator());
- this.configuration.setMdSal(configuration.isMdSal());
- this.configuration.setRpcConfigFile(configuration.getRpcConfigFile());
- this.configuration.setInitialConfigXMLFile(configuration.getInitialConfigXMLFile());
- this.configuration.setNotificationFile(configuration.getNotificationFile());
- this.configuration.setSchemasDir(configuration.getSchemasDir());
- this.configuration.setDefaultYangResources(configuration.getDefaultYangResources());
- this.configuration.setAuthProvider(configuration.getAuthProvider());
- this.configuration.setPublickeyAuthenticator(configuration.getPublickeyAuthenticator());
+ public ConfigurationBuilder from(final Configuration template) {
+ this.configuration.setThreadPoolSize(template.getThreadPoolSize());
+ this.configuration.setGenerateConfigsTimeout(template.getGenerateConfigsTimeout());
+ this.configuration.setModels(template.getModels());
+ this.configuration.setCapabilities(template.getCapabilities());
+ this.configuration.setStartingPort(template.getStartingPort());
+ this.configuration.setDeviceCount(template.getDeviceCount());
+ this.configuration.setSsh(template.isSsh());
+ this.configuration.setIp(template.getIp());
+ this.configuration.setRpcHandler(template.getRpcHandler());
+ this.configuration.setOperationsCreator(template.getOperationsCreator());
+ this.configuration.setMdSal(template.isMdSal());
+ this.configuration.setRpcConfigFile(template.getRpcConfigFile());
+ this.configuration.setInitialConfigXMLFile(template.getInitialConfigXMLFile());
+ this.configuration.setNotificationFile(template.getNotificationFile());
+ this.configuration.setSchemasDir(template.getSchemasDir());
+ this.configuration.setDefaultYangResources(template.getDefaultYangResources());
+ this.configuration.setAuthProvider(template.getAuthProvider());
+ this.configuration.setPublickeyAuthenticator(template.getPublickeyAuthenticator());
return this;
}
- public ConfigurationBuilder from(TesttoolParameters testtoolParameters) {
+ public ConfigurationBuilder from(final TesttoolParameters testtoolParameters) {
this.configuration.setGenerateConfigsTimeout(testtoolParameters.generateConfigsTimeout);
this.configuration.setStartingPort(testtoolParameters.startingPort);
this.configuration.setDeviceCount(testtoolParameters.deviceCount);
private final XmlElement xmlElement;
private final int hashCode;
- private Request(final XmlElement element) {
+ Request(final XmlElement element) {
this.xmlElement = element;
hashCode = XmlUtil.toString(element)
.replaceAll("message-id=.*(>| )", "") //message id is variable, remove it
private final SettableRpc rpc;
- private SettableOperationService(final File rpcConfig) {
+ SettableOperationService(final File rpcConfig) {
this.rpc = new SettableRpc(rpcConfig);
}
}
}
- private void checkForError(final Document document) throws DocumentedException {
+ private static void checkForError(final Document document) throws DocumentedException {
final XmlElement rpcReply = XmlElement.fromDomDocument(document);
if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) {
throw DocumentedException.fromXMLDocument(document);
import org.opendaylight.netconf.test.tool.rpc.SimulatedLock;
import org.opendaylight.netconf.test.tool.rpc.SimulatedUnLock;
-public class DefaultOperationsCreator implements OperationsCreator {
+public final class DefaultOperationsCreator implements OperationsCreator {
private final SimulatedOperationService simulatedOperationService;
public SimulatedCreateSubscription(final String id, final Optional<File> notificationsFile) {
super(id);
- Optional<Notifications> notifications;
+ Optional<Notifications> notifs;
if (notificationsFile.isPresent()) {
- notifications = Optional.of(loadNotifications(notificationsFile.get()));
+ notifs = Optional.of(loadNotifications(notificationsFile.get()));
scheduledExecutorService = Executors.newScheduledThreadPool(1);
} else {
- notifications = Optional.absent();
+ notifs = Optional.absent();
}
- if (notifications.isPresent()) {
+ if (notifs.isPresent()) {
Map<Notification, NetconfMessage> preparedMessages = Maps.newHashMapWithExpectedSize(
- notifications.get().getNotificationList().size());
- for (final Notification notification : notifications.get().getNotificationList()) {
+ notifs.get().getNotificationList().size());
+ for (final Notification notification : notifs.get().getNotificationList()) {
final NetconfMessage parsedNotification = parseNetconfNotification(notification.getContent());
preparedMessages.put(notification, parsedNotification);
}
}
- private Notifications loadNotifications(final File file) {
+ private static Notifications loadNotifications(final File file) {
try {
final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class);
final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
delayAggregator += notification.getKey().getDelayInSeconds();
- scheduledExecutorService.schedule(new Runnable() {
- @Override
- public void run() {
- Preconditions.checkState(session != null, "Session is not set, cannot process notifications");
- session.sendMessage(notification.getValue());
- }
+ scheduledExecutorService.schedule(() -> {
+ Preconditions.checkState(session != null, "Session is not set, cannot process notifications");
+ session.sendMessage(notification.getValue());
}, delayAggregator, TimeUnit.SECONDS);
}
}
}
@Override
- public void setNetconfSession(final NetconfServerSession session) {
- this.session = session;
+ public void setNetconfSession(final NetconfServerSession newSession) {
+ this.session = newSession;
}
@XmlRootElement(name = "notifications")
}
}
- private DataList loadInitialConfigXMLFile(final File file) {
+ private static DataList loadInitialConfigXMLFile(final File file) {
LOG.info("Loading initial config xml file: {}", file.getName());
DataList configData = new DataList();
List<XmlElement> xmlElementList = Collections.emptyList();
private final SettableRpc rpc;
- private SettableOperationService(RpcHandler rpcHandler) {
+ SettableOperationService(RpcHandler rpcHandler) {
this.rpc = new SettableRpc(rpcHandler);
}
private final RpcHandler rpcHandler;
- SettableRpc(RpcHandler rpcHandler) {
+ SettableRpc(final RpcHandler rpcHandler) {
this.rpcHandler = rpcHandler;
}
}
}
- private void checkForError(final Document document) throws DocumentedException {
+ private static void checkForError(final Document document) throws DocumentedException {
final XmlElement rpcReply = XmlElement.fromDomDocument(document);
if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) {
throw DocumentedException.fromXMLDocument(document);
package org.opendaylight.netconf.test.tool.schemacache;
import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.netconf.test.tool.TestToolUtils;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
private static final Logger LOG = LoggerFactory.getLogger(SchemaSourceCache.class);
- public static final Pattern CACHED_FILE_PATTERN =
- Pattern.compile(
- ".*/(?<moduleName>[^@]+)" + "(@(?<revision>" + SourceIdentifier.REVISION_PATTERN + "))?.yang");
+ public static final Pattern CACHED_FILE_PATTERN = Pattern.compile(
+ ".*/(?<moduleName>[^@]+)" + "(@(?<revision>" + Revision.STRING_FORMAT_PATTERN + "))?.yang");
private final Class<T> representation;
private final Set<String> modelList;
}
@Override
- public synchronized CheckedFuture<? extends T, SchemaSourceException> getSource(
- final SourceIdentifier sourceIdentifier) {
+ public synchronized ListenableFuture<? extends T> getSource(final SourceIdentifier sourceIdentifier) {
ModelData modelData = cachedSchemas.get(sourceIdentifier.toYangFilename());
if (modelData != null) {
final SchemaSourceRepresentation restored = restoreAsType(modelData.getId(), modelData.getPath());
- return Futures.immediateCheckedFuture(representation.cast(restored));
- } else {
- LOG.debug("Source {} not found in cache as {}", sourceIdentifier);
- return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found",
- sourceIdentifier));
+ return Futures.immediateFuture(representation.cast(restored));
}
+
+ LOG.debug("Source {} not found in cache as {}", sourceIdentifier);
+ return Futures.immediateFailedFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
}
@Override
LOG.trace("Source {} offered to cache", source.getIdentifier());
}
- private YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final String cachedSource) {
+ private static YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier,
+ final String cachedSource) {
return new YangTextSchemaSource(sourceIdentifier) {
@Override
final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
if (matcher.matches()) {
final String moduleName = matcher.group("moduleName");
- final String revision = matcher.group("revision");
- return Optional.of(RevisionSourceIdentifier.create(moduleName, Optional.fromNullable(revision)));
+ final Optional<Revision> revision = Revision.ofNullable(matcher.group("revision"));
+ return Optional.of(RevisionSourceIdentifier.create(moduleName, revision));
}
- return Optional.absent();
+ return Optional.empty();
}
-
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
* 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.yanglib.impl;
import com.google.common.base.Preconditions;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
/**
* Listens on new schema sources registered event. For each new source
* registered generates URL representing its schema source and write this URL
}
private static String revString(final SourceIdentifier id) {
- final String rev = id.getRevision();
- return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? "" : rev;
+ return id.getRevision().map(Revision::toString).orElse("");
}
private static OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) {
- final String rev = sourceIdentifier.getRevision();
- return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? NO_REVISION
- : new OptionalRevision(new RevisionIdentifier(rev));
+ return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString())))
+ .orElse(NO_REVISION);
}
private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
package org.opendaylight.yanglib.impl;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
+import java.util.concurrent.ExecutionException;
import org.opendaylight.yanglib.api.YangLibService;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
-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.slf4j.Logger;
public String getSchema(final String name, final String revision) {
Preconditions.checkNotNull(schemaRepository, "Schema repository is not initialized");
LOG.debug("Attempting load for schema source {}:{}", name, revision);
- final SourceIdentifier sourceId =
- RevisionSourceIdentifier.create(name, Optional.fromNullable(revision.equals("") ? null : revision));
+ final SourceIdentifier sourceId = RevisionSourceIdentifier.create(name,
+ revision.isEmpty() ? null : Revision.of(revision));
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> sourceFuture =
- schemaRepository.getSchemaSource(sourceId, YangTextSchemaSource.class);
+ final ListenableFuture<YangTextSchemaSource> sourceFuture = schemaRepository.getSchemaSource(sourceId,
+ YangTextSchemaSource.class);
try {
- final YangTextSchemaSource source = sourceFuture.checkedGet();
+ final YangTextSchemaSource source = sourceFuture.get();
return new String(ByteStreams.toByteArray(source.openStream()));
- } catch (SchemaSourceException | IOException e) {
- throw new IllegalStateException("Unable to get schema" + sourceId, e);
+ } catch (InterruptedException | ExecutionException | IOException e) {
+ throw new IllegalStateException("Unable to get schema " + sourceId, e);
}
}
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfigBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.opendaylight.yangtools.yang.model.repo.api.YinSchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
public class YangLibProviderTest {
private static final File CACHE_DIR = new File("target/yanglib");
list.add(
PotentialSchemaSource.create(
- RevisionSourceIdentifier.create("with-revision", "2016-04-28"),
+ RevisionSourceIdentifier.create("with-revision", Revision.of("2016-04-28")),
YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
when(writeTransaction.submit()).thenReturn(Futures.immediateCheckedFuture(null));
yangUnregistererSource =
PotentialSchemaSource.create(
- RevisionSourceIdentifier.create("unregistered-yang-with-revision", "2016-04-28"),
+ RevisionSourceIdentifier.create("unregistered-yang-with-revision", Revision.of("2016-04-28")),
YangTextSchemaSource.class, PotentialSchemaSource.Costs.LOCAL_IO.getValue());
yangLibProvider.schemaSourceUnregistered(yangUnregistererSource);
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import com.google.common.base.MoreObjects;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
final YangLibServiceImpl yangLibService = new YangLibServiceImpl();
yangLibService.setSchemaRepository(schemaRepository);
- final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("name", "2016-01-01");
+ final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("name", Revision.of("2016-01-01"));
final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) {
@Override
- protected MoreObjects.ToStringHelper addToStringAttributes(MoreObjects.ToStringHelper toStringHelper) {
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return null;
}
}
};
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> sourceFuture =
- Futures.immediateCheckedFuture(yangTextSchemaSource);
+ final ListenableFuture<YangTextSchemaSource> sourceFuture = Futures.immediateFuture(yangTextSchemaSource);
doReturn(sourceFuture).when(schemaRepository).getSchemaSource(any(SourceIdentifier.class),
eq(YangTextSchemaSource.class));
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>mockito-configuration</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
this.status = status;
}
- private RestconfDocumentedException(final Throwable cause, final RestconfError error) {
+ public RestconfDocumentedException(final Throwable cause, final RestconfError error) {
super(cause);
Preconditions.checkNotNull(error, "RestconfError can't be null");
errors = ImmutableList.of(error);
package org.opendaylight.restconf.common.util;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
/**
private static SchemaNode mockSchemaNode(final String origKey) {
final SchemaNode mockSchNode = Mockito.mock(SchemaNode.class);
Mockito.when(mockSchNode.getQName())
- .thenReturn(QName.create("ns", SimpleDateFormatUtil.getRevisionFormat().format(new Date()), origKey));
+ .thenReturn(QName.create("ns", "2016-10-10", origKey));
return mockSchNode;
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import java.util.concurrent.ExecutionException;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import org.opendaylight.restconf.common.schema.SchemaExportContext;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
@Provider
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
WebApplicationException {
final RevisionSourceIdentifier sourceId = RevisionSourceIdentifier.create(context.getModule().getName(),
- context.getModule().getQNameModule().getFormattedRevision());
+ context.getModule().getQNameModule().getRevision());
final YangTextSchemaSource yangTextSchemaSource;
try {
- yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).checkedGet();
- } catch (SchemaSourceException e) {
+ yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).get();
+ } catch (InterruptedException | ExecutionException e) {
throw new WebApplicationException("Unable to retrieve source from SourceProvider.", e);
}
yangTextSchemaSource.copyTo(entityStream);
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
-import java.text.ParseException;
-import java.util.Date;
+import java.time.format.DateTimeParseException;
import java.util.Iterator;
import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.restconf.common.schema.SchemaExportContext;
import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
final String moduleName, final String revisionStr,
final DOMYangTextSourceProvider yangTextSourceProvider) {
try {
- final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse(revisionStr);
- final Module module = schemaContext.findModuleByName(moduleName, revision);
-
+ final Module module = schemaContext.findModule(moduleName, Revision.of(revisionStr)).orElse(null);
return new SchemaExportContext(
schemaContext, RestconfValidationUtils.checkNotNullDocumented(module, moduleName),
yangTextSourceProvider);
- } catch (final ParseException e) {
+ } catch (final DateTimeParseException e) {
throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
}
}
import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
import org.opendaylight.yangtools.yang.common.QName;
/**
* This class just delegates all of the functionality to Yangtools normalized node writer.
*/
-public class RestconfDelegatingNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
+public final class RestconfDelegatingNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
private NormalizedNodeWriter delegNNWriter;
private RestconfDelegatingNormalizedNodeWriter(NormalizedNodeStreamWriter streamWriter, final boolean
@Override
protected Module moduleForPrefix(@Nonnull final String prefix) {
if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) {
- return this.context.findModuleByName(this.defaultPrefix, null);
+ return this.context.findModules(this.defaultPrefix).stream().findFirst().orElse(null);
} else {
- return this.context.findModuleByName(prefix, null);
+ return this.context.findModules(prefix).stream().findFirst().orElse(null);
}
}
@Nullable
@Override
protected String prefixForNamespace(@Nonnull final URI namespace) {
- final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null);
- return module == null ? null : module.getName();
+ return this.context.findModules(namespace).stream().findFirst().map(Module::getName).orElse(null);
}
}
\ No newline at end of file
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
}
while (!foundSchemaNodes.isEmpty()) {
final Object child = foundSchemaNodes.pop();
- if (child instanceof AugmentationSchema) {
- final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
+ if (child instanceof AugmentationSchemaNode) {
+ final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
} else if (child instanceof DataSchemaNode) {
schemaNode = (DataSchemaNode) child;
// find augmentation
if (child.isAugmenting()) {
- final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
+ final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
if (augment != null) {
result.push(augment);
}
}
for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
- for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
+ for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
if (!resultFromRecursion.isEmpty()) {
resultFromRecursion.push(choiceNode);
if (choiceNode.isAugmenting()) {
- final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
+ final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
if (augment != null) {
resultFromRecursion.push(augment);
}
return result;
}
- private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
+ private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
final DataSchemaNode child) {
- if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
- for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
+ if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
+ for (final AugmentationSchemaNode augmentation :
+ ((AugmentationTarget) parent).getAvailableAugmentations()) {
final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
if (childInAugmentation != null) {
return augmentation;
import org.opendaylight.restconf.common.util.RestUtil;
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.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
LOG.debug("Error parsing xml input", e);
throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE);
+ ErrorTag.MALFORMED_MESSAGE, e);
}
}
? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
// find module according to namespace
- final Module module = pathContext.getSchemaContext().findModuleByNamespace(
- URI.create(namespace)).iterator().next();
+ final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
// initialize codec + set default prefix derived from module name
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
} else {
targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
.concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
- namespace, module.getQNameModule().getFormattedRevision())));
+ namespace,
+ module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
private DOMDataBroker domDataBroker;
private DOMNotificationService domNotification;
- private BrokerFacade() {}
+ BrokerFacade() {
+
+ }
public void setRpcService(final DOMRpcService router) {
this.rpcService = router;
}
- public void setDomNotificationService(final DOMNotificationService domNotification) {
- this.domNotification = domNotification;
+ public void setDomNotificationService(final DOMNotificationService service) {
+ this.domNotification = service;
}
public static BrokerFacade getInstance() {
throw new RestconfDocumentedException(
error.getMessage(),
ErrorType.TRANSPORT,
- ErrorTag.RESOURCE_DENIED_TRANSPORT);
+ ErrorTag.RESOURCE_DENIED_TRANSPORT, e);
}
}
throw new RestconfDocumentedException("Error reading data.", e, e.getErrorList());
((ListSchemaNode) childSchema).getKeyDefinition());
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
- final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
- final String nodeVal = ((LeafNode<String>) child).getValue();
+ final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
+ final Object nodeVal = ((LeafNode<?>) child).getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (keys.contains(child.getNodeType())) {
((ListSchemaNode) childSchema).getKeyDefinition());
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
- final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
- final String nodeVal = ((LeafNode<String>) child).getValue();
+ final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
+ final Object nodeVal = ((LeafNode<?>) child).getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (trim) {
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
+import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.util.RestUtil;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
this.yangTextSourceProvider = yangTextSourceProvider;
}
- private ControllerContext() {
+ ControllerContext() {
+
}
public static ControllerContext getInstance() {
}
final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
- final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
+ final Set<Module> latestModule = this.globalSchema.findModules(startModule);
- if (latestModule == null) {
+ if (latestModule.isEmpty()) {
throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
}
final InstanceIdentifierContext<?> iiWithSchemaNode =
- collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier);
+ collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
if (iiWithSchemaNode == null) {
throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
public Module findModuleByName(final String moduleName) {
checkPreconditions();
- Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
- return this.globalSchema.findModuleByName(moduleName, null);
+ Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
+ return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
}
public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
- Preconditions.checkArgument((moduleName != null) && (mountPoint != null));
+ Preconditions.checkArgument(moduleName != null && mountPoint != null);
final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
if (mountPointSchema == null) {
return null;
}
- return mountPointSchema.findModuleByName(moduleName, null);
+ return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
}
public Module findModuleByNamespace(final URI namespace) {
checkPreconditions();
Preconditions.checkArgument(namespace != null);
- return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null);
+ return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
}
public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
- Preconditions.checkArgument((namespace != null) && (mountPoint != null));
+ Preconditions.checkArgument(namespace != null && mountPoint != null);
final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
if (mountPointSchema == null) {
return null;
}
- return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
+ return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
}
- public Module findModuleByNameAndRevision(final QName module) {
+ public Module findModuleByNameAndRevision(final String name, final Revision revision) {
checkPreconditions();
- Preconditions
- .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
+ Preconditions.checkArgument(name != null && revision != null);
- return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
+ return this.globalSchema.findModule(name, revision).orElse(null);
}
- public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
+ public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
+ final Revision revision) {
checkPreconditions();
- Preconditions
- .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
- && (mountPoint != null));
+ Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
final SchemaContext schemaContext = mountPoint.getSchemaContext();
- return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
- module.getRevision());
+ return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
}
public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
final Iterable<PathArgument> elements = path.getPathArguments();
final PathArgument head = elements.iterator().next();
final QName startQName = head.getNodeType();
- final Module initialModule = this.globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
- startQName.getRevision());
+ final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
DataNodeContainer node = initialModule;
for (final PathArgument element : elements) {
final QName _nodeType = element.getNodeType();
final DataSchemaNode potentialNode = childByQName(node, _nodeType);
- if ((potentialNode == null) || !isListOrContainer(potentialNode)) {
+ if (potentialNode == null || !isListOrContainer(potentialNode)) {
return null;
}
node = (DataNodeContainer) potentialNode;
} else {
schemaContext = this.globalSchema;
}
- final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
- startQName.getRevision());
+ final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
DataNodeContainer node = initialModule;
for (final PathArgument element : elements) {
if (!(element instanceof AugmentationIdentifier)) {
final QName _nodeType = element.getNodeType();
final DataSchemaNode potentialNode = childByQName(node, _nodeType);
- if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode))
+ if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
&& !(potentialNode instanceof ChoiceSchemaNode)) {
builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
if (potentialNode instanceof DataNodeContainer) {
}
private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
- final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
+ final Module schema = context.findModule(qname.getModule()).orElse(null);
return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
}
}
public Module getRestconfModule() {
- return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME);
+ return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
}
public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
} else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
} else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
final DataSchemaNode modules = Iterables.getFirst(instances, null);
- instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
+ instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
RestConfModule.STREAM_LIST_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
} else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
} else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
final DataSchemaNode modules = Iterables.getFirst(instances, null);
- instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
+ instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
RestConfModule.MODULE_LIST_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
} else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
- ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
return Iterables.getFirst(instances, null);
}
}
private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
- for (final ChoiceCaseNode caze : container.getCases()) {
+ for (final CaseSchemaNode caze : container.getCases().values()) {
final DataSchemaNode ret = childByQName(caze, name);
if (ret != null) {
return ret;
return null;
}
- private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
+ private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
return container.getDataChildByName(name);
}
private static DataSchemaNode childByQName(final Object container, final QName name) {
- if (container instanceof ChoiceCaseNode) {
- return childByQName((ChoiceCaseNode) container, name);
+ if (container instanceof CaseSchemaNode) {
+ return childByQName((CaseSchemaNode) container, name);
} else if (container instanceof ChoiceSchemaNode) {
return childByQName((ChoiceSchemaNode) container, name);
} else if (container instanceof ContainerSchemaNode) {
final DataSchemaNode ret = container.getDataChildByName(name);
if (ret == null) {
for (final DataSchemaNode node : container.getChildNodes()) {
- if ((node instanceof ChoiceSchemaNode)) {
- final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
+ if (node instanceof ChoiceSchemaNode) {
+ final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
final DataSchemaNode childByQName = childByQName(choiceNode, name);
if (childByQName != null) {
return childByQName;
}
if (strings.isEmpty()) {
- return createContext(builder.build(), ((DataSchemaNode) parentNode),
+ return createContext(builder.build(), (DataSchemaNode) parentNode,
mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
}
ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
}
- if (returnJustMountPoint || (strings.size() == 1)) {
+ if (returnJustMountPoint || strings.size() == 1) {
final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
}
ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
}
- final Module moduleBehindMountPoint =
- mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
- if (moduleBehindMountPoint == null) {
+ final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
+ if (!it.hasNext()) {
throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
+ "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
}
final List<String> subList = strings.subList(1, strings.size());
- return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
+ return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
returnJustMountPoint);
}
Module module = null;
if (mountPoint == null) {
checkPreconditions();
- module = this.globalSchema.findModuleByName(moduleName, null);
+ module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
if (module == null) {
throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
} else {
final SchemaContext schemaContext = mountPoint.getSchemaContext();
if (schemaContext != null) {
- module = schemaContext.findModuleByName(moduleName, null);
+ module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
} else {
module = null;
}
targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
- if ((targetNode == null) && (parentNode instanceof Module)) {
+ if (targetNode == null && parentNode instanceof Module) {
final RpcDefinition rpc;
if (mountPoint == null) {
rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
}
int consumed = 1;
- if ((targetNode instanceof ListSchemaNode)) {
- final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
+ if (targetNode instanceof ListSchemaNode) {
+ final ListSchemaNode listNode = (ListSchemaNode) targetNode;
final int keysSize = listNode.getKeyDefinition().size();
- if ((strings.size() - consumed) < keysSize) {
+ if (strings.size() - consumed < keysSize) {
throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
+ "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
}
builder.node(targetNode.getQName());
}
- if ((targetNode instanceof DataNodeContainer)) {
+ if (targetNode instanceof DataNodeContainer) {
final List<String> remaining = strings.subList(consumed, strings.size());
- return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
+ return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
returnJustMountPoint);
}
final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
ChoiceSchemaNode.class);
- final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
- for (final ChoiceCaseNode caze : Iterables.concat(map)) {
+ final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
+ choice -> choice.getCases().values());
+ for (final CaseSchemaNode caze : Iterables.concat(map)) {
collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
}
}
public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
- return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
- || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
- || (node instanceof AnyXmlSchemaNode);
+ return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
+ || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
+ || node instanceof AnyXmlSchemaNode;
}
private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
final DOMMountPoint mountPoint) {
Preconditions.checkNotNull(uriValue);
- Preconditions.checkArgument((node instanceof LeafSchemaNode));
+ Preconditions.checkArgument(node instanceof LeafSchemaNode);
final String urlDecoded = urlPathArgDecode(uriValue);
TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
Object decoded = codec.deserialize(urlDecoded);
String additionalInfo = "";
if (decoded == null) {
- if ((typedef instanceof IdentityrefTypeDefinition)) {
+ if (typedef instanceof IdentityrefTypeDefinition) {
final SchemaContext schemaContext =
mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
- decoded = toQName(schemaContext, urlDecoded, null);
+ decoded = toQName(schemaContext, urlDecoded);
additionalInfo =
"For key which is of type identityref it should be in format module_name:identity_name.";
}
return str.substring(idx + 1);
}
- private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) {
+ private QName toQName(final SchemaContext schemaContext, final String name,
+ final java.util.Optional<Revision> revisionDate) {
checkPreconditions();
final String module = toModuleName(name);
final String node = toNodeName(name);
- final Module m = schemaContext.findModuleByName(module, revisionDate);
+ final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
return m == null ? null : QName.create(m.getQNameModule(), node);
}
+ private QName toQName(final SchemaContext schemaContext, final String name) {
+ checkPreconditions();
+ final String module = toModuleName(name);
+ final String node = toNodeName(name);
+ final Set<Module> modules = schemaContext.findModules(module);
+ return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
+ }
+
private static boolean isListOrContainer(final DataSchemaNode node) {
- return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode);
+ return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
}
- public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
+ public RpcDefinition getRpcDefinition(final String name, final java.util.Optional<Revision> revisionDate) {
final QName validName = toQName(this.globalSchema, name, revisionDate);
return validName == null ? null : this.qnameToRpc.get().get(validName);
}
+ public RpcDefinition getRpcDefinition(final String name) {
+ final QName validName = toQName(this.globalSchema, name);
+ return validName == null ? null : this.qnameToRpc.get().get(validName);
+ }
+
private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
for (final RpcDefinition rpcDefinition : module.getRpcs()) {
return decodedPathArgs;
} catch (final UnsupportedEncodingException e) {
throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
}
}
return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
} catch (final UnsupportedEncodingException e) {
throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
}
}
final DOMMountPoint mount) {
if (argument instanceof NodeIdentifier) {
return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
- } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) {
+ } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
(ListSchemaNode) node, mount);
- } else if ((argument != null) && (node != null)) {
+ } else if (argument != null && node != null) {
throw new IllegalArgumentException("Conversion of generic path argument is not supported");
} else {
throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
}
@Override
- public DataSchemaNode getDataChildByName(final QName name) {
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
for (final DataSchemaNode node : this.children) {
if (node.getQName().equals(name)) {
- return node;
+ return Optional.of(node);
}
}
throw new RestconfDocumentedException(name + " is not in child of " + PATH.getLastComponent());
}
@Override
- public Set<AugmentationSchema> getAvailableAugmentations() {
+ public Set<AugmentationSchemaNode> getAvailableAugmentations() {
return new HashSet<>();
}
return false;
}
- @Override
- public ConstraintDefinition getConstraints() {
- throw new UnsupportedOperationException("Not supported.");
- }
-
@Override
public QName getQName() {
return PATH.getLastComponent();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Not supported.");
}
public boolean isPresenceContainer() {
throw new UnsupportedOperationException("Not supported.");
}
+
+ @Override
+ public Optional<RevisionAwareXPath> getWhenCondition() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Set<NotificationDefinition> getNotifications() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Set<ActionDefinition> getActions() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
}
import com.google.common.collect.ImmutableSet;
import java.net.URI;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
+import org.opendaylight.yangtools.concepts.SemVer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Deviation;
import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
return ImmutableSet.of();
}
- @Override
- public DataSchemaNode getDataChildByName(final QName name) {
- return null;
- }
-
@Override
public Set<UsesNode> getUses() {
return ImmutableSet.of();
}
- @Override
- public String getModuleSourcePath() {
- return null;
- }
-
@Override
public QNameModule getQNameModule() {
return delegate.getQNameModule();
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return delegate.getRevision();
}
}
@Override
- public String getYangVersion() {
+ public YangVersion getYangVersion() {
return delegate.getYangVersion();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
return delegate.getDescription();
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
return delegate.getReference();
}
@Override
- public String getOrganization() {
+ public Optional<String> getOrganization() {
return delegate.getOrganization();
}
@Override
- public String getContact() {
+ public Optional<String> getContact() {
return delegate.getContact();
}
}
@Override
- public Set<AugmentationSchema> getAugmentations() {
+ public Set<AugmentationSchemaNode> getAugmentations() {
return ImmutableSet.of();
}
}
@Override
- public String getSource() {
- return null;
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
+ return Optional.empty();
+ }
+
+ @Override
+ public Set<NotificationDefinition> getNotifications() {
+ return delegate.getNotifications();
+ }
+
+ @Override
+ public Optional<SemVer> getSemanticVersion() {
+ return delegate.getSemanticVersion();
}
}
*/
package org.opendaylight.netconf.sal.restconf.impl;
+import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
return false;
}
- @Override
- public ConstraintDefinition getConstraints() {
- throw new UnsupportedOperationException("Not supported.");
- }
-
@Override
public QName getQName() {
return path.getLastComponent();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Not supported.");
}
}
@Override
- public String getDefault() {
+ public Optional<RevisionAwareXPath> getWhenCondition() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
- public String getUnits() {
+ public boolean isMandatory() {
throw new UnsupportedOperationException("Not supported.");
}
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
}
package org.opendaylight.netconf.sal.restconf.impl;
import com.google.common.base.Preconditions;
-import java.util.Date;
+import java.util.Optional;
+import org.opendaylight.yangtools.concepts.SemVer;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.ModuleImport;
/**
- * Fake {@link ModuleImport} implementation used to attach corrent prefix mapping to fake RPCs.
+ * Fake {@link ModuleImport} implementation used to attach current prefix mapping to fake RPCs.
*
* @author Robert Varga
*/
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return module.getRevision();
}
public String getPrefix() {
return module.getName();
}
+
+ @Override
+ public Optional<String> getDescription() {
+ return module.getDescription();
+ }
+
+ @Override
+ public Optional<String> getReference() {
+ return module.getReference();
+ }
+
+ @Override
+ public Optional<SemVer> getSemanticVersion() {
+ return module.getSemanticVersion();
+ }
}
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
+import org.opendaylight.yangtools.concepts.SemVer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Deviation;
*/
final class FakeRestconfModule implements Module {
- static final QNameModule QNAME;
-
- static {
- Date date;
- try {
- date = SimpleDateFormatUtil.getRevisionFormat().parse("2016-06-28");
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), date).intern();
- }
+ static final QNameModule QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"),
+ Revision.of("2016-06-28")).intern();
private final Collection<DataSchemaNode> children;
private final ImmutableSet<ModuleImport> imports;
}
@Override
- public DataSchemaNode getDataChildByName(final QName name) {
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
for (final DataSchemaNode node : this.children) {
if (node.getQName().equals(name)) {
- return node;
+ return Optional.of(node);
}
}
throw new RestconfDocumentedException(name + " is not in child of " + FakeRestconfModule.QNAME);
throw new UnsupportedOperationException("Not supported operations.");
}
- @Override
- public String getModuleSourcePath() {
- throw new UnsupportedOperationException("Not supported operations.");
- }
-
@Override
public QNameModule getQNameModule() {
return QNAME;
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return QNAME.getRevision();
}
}
@Override
- public String getYangVersion() {
+ public YangVersion getYangVersion() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getOrganization() {
+ public Optional<String> getOrganization() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getContact() {
+ public Optional<String> getContact() {
throw new UnsupportedOperationException("Not supported operations.");
}
}
@Override
- public Set<AugmentationSchema> getAugmentations() {
+ public Set<AugmentationSchemaNode> getAugmentations() {
throw new UnsupportedOperationException("Not supported operations.");
}
}
@Override
- public String getSource() {
+ public Optional<SemVer> getSemanticVersion() {
throw new UnsupportedOperationException("Not supported operations.");
}
-
}
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError;
-public class QueryParametersParser {
+public final class QueryParametersParser {
private enum UriParameters {
PRETTY_PRINT("prettyPrint"),
}
}
+ private QueryParametersParser() {
+
+ }
+
public static WriterParameters parseWriterParameters(final UriInfo info) {
return parseParams(info, false);
}
}
wpBuilder.setDepth(depth);
} catch (final NumberFormatException e) {
- throw new RestconfDocumentedException(new RestconfError(
+ throw new RestconfDocumentedException(e, new RestconfError(
RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
"Invalid depth parameter: " + e.getMessage(), null,
"The depth parameter must be an integer > 1 or \"unbounded\""));
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RestCodec {
+public final class RestCodec {
private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
private RestCodec() {
}
- public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+ public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
final DOMMountPoint mountPoint) {
return new ObjectCodec(typeDefinition, mountPoint);
}
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import java.net.URI;
-import java.text.ParseException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
+import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RestconfImpl implements RestconfService {
+public final class RestconfImpl implements RestconfService {
private static final RestconfImpl INSTANCE = new RestconfImpl();
private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
- private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
+ private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
NETCONF_BASE_PAYLOAD_NAME).intern();
- private static final QNameModule SAL_REMOTE_AUGMENT;
-
- static {
- try {
- SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
+ private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
+ Revision.of("2014-07-08"));
private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
new AugmentationIdentifier(ImmutableSet.of(
@Override
public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
Preconditions.checkNotNull(identifier);
- final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
+ final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
Module module = null;
DOMMountPoint mountPoint = null;
final SchemaContext schemaContext;
final InstanceIdentifierContext<?> mountPointIdentifier =
this.controllerContext.toMountPointIdentifier(identifier);
mountPoint = mountPointIdentifier.getMountPoint();
- module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
+ module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
+ nameRev.getValue());
schemaContext = mountPoint.getSchemaContext();
} else {
- module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
+ module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
schemaContext = this.controllerContext.getGlobalSchema();
}
if (module == null) {
- final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
- + moduleNameAndRevision.getRevision() + "' was not found.";
+ final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
+ + nameRev.getValue() + "' was not found.";
LOG.debug(errMsg);
throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
}
return restconfModule;
}
- private static QName getModuleNameAndRevision(final String identifier) {
+ private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
String moduleNameAndRevision = "";
if (mountIndex >= 0) {
moduleNameAndRevision = identifier;
}
- final Splitter splitter = Splitter.on("/").omitEmptyStrings();
- final Iterable<String> split = splitter.split(moduleNameAndRevision);
- final List<String> pathArgs = Lists.<String>newArrayList(split);
+ final Splitter splitter = Splitter.on('/').omitEmptyStrings();
+ final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
if (pathArgs.size() < 2) {
LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
throw new RestconfDocumentedException(
}
try {
- final String moduleName = pathArgs.get(0);
- final String revision = pathArgs.get(1);
- return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
- } catch (final ParseException e) {
+ return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
+ } catch (final DateTimeParseException e) {
LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
}
}
RpcDefinition rpc = null;
if (mountPoint == null) {
- rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
+ rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
} else {
rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
}
result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
}
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
if (response == null) {
return null;
} catch (final InterruptedException e) {
final String errMsg = "The operation was interrupted while executing and did not complete.";
LOG.debug("Rpc Interrupt - " + errMsg, e);
- throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
+ throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
} catch (final ExecutionException e) {
LOG.debug("Execution RpcError: ", e);
Throwable cause = e.getCause();
invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
final ContainerNode value = (ContainerNode) payload.getData();
final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
- final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
- QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
+ new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
+ "path")));
final Object pathValue = path.isPresent() ? path.get().getValue() : null;
if (!(pathValue instanceof YangInstanceIdentifier)) {
final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
if (searchedException.isPresent()) {
- throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
- ErrorTag.DATA_MISSING);
+ throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
+ ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
}
final String errMsg = "Error while deleting data";
final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
- .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
+ .findModule(qnameBase.getModule()).orElse(null)
.getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
final List<PathArgument> path = new ArrayList<>();
path.add(NodeIdentifier.create(qnameBase));
return this.broker.patchConfigurationDataWithinTransaction(context);
} catch (final Exception e) {
LOG.debug("Patch transaction failed", e);
- throw new RestconfDocumentedException(e.getMessage());
+ throw new RestconfDocumentedException(e.getMessage(), e);
}
}
return this.broker.patchConfigurationDataWithinTransaction(context);
} catch (final Exception e) {
LOG.debug("Patch transaction failed", e);
- throw new RestconfDocumentedException(e.getMessage());
+ throw new RestconfDocumentedException(e.getMessage(), e);
}
}
*/
private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
final String paramName) {
- final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
SAL_REMOTE_AUG_IDENTIFIER);
if (!optAugNode.isPresent()) {
return null;
if (!(augNode instanceof AugmentationNode)) {
return null;
}
- final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
- new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
+ .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
if (!enumNode.isPresent()) {
return null;
}
ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
- final String revision = module.getQNameModule().getFormattedRevision();
- moduleNodeValues
- .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
+ final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
+ if (revision.isPresent()) {
+ moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
+ .withValue(revision.get().toString()).build());
+ }
instanceDataChildrenByName =
ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
import org.opendaylight.restconf.common.patch.PatchContext;
import org.opendaylight.restconf.common.patch.PatchStatusContext;
-public class StatisticsRestconfServiceWrapper implements RestconfService {
+public final class StatisticsRestconfServiceWrapper implements RestconfService {
AtomicLong operationalGet = new AtomicLong();
AtomicLong configGet = new AtomicLong();
public BigInteger getFailureDelete() {
return BigInteger.valueOf(this.failureDelete.get());
}
-}
\ No newline at end of file
+}
* @param leafNodesOnly
* if true, notifications will contain changes to leaf nodes only
*/
+ @SuppressWarnings("checkstyle:hiddenField")
public void setQueryParams(final Instant start, final Optional<Instant> stop, final Optional<String> filter,
final boolean leafNodesOnly) {
this.start = Preconditions.checkNotNull(start);
*/
package org.opendaylight.netconf.sal.streams.listeners;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.Collection;
private final String streamName;
private final NotificationOutputType outputType;
- private Collection<DataTreeCandidate> dataTreeCandidates;
+ private Collection<DataTreeCandidate> candidates;
/**
* Creates new {@link ListenerAdapter} listener specified by path and stream
register(this);
this.outputType = Preconditions.checkNotNull(outputType);
this.path = Preconditions.checkNotNull(path);
- Preconditions.checkArgument((streamName != null) && !streamName.isEmpty());
+ Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
this.streamName = streamName;
}
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeCandidate> dataTreeCandidates) {
- this.dataTreeCandidates = dataTreeCandidates;
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> dataTreeCandidates) {
+ this.candidates = dataTreeCandidates;
final String xml = prepareXml();
if (checkQueryParams(xml, this)) {
prepareAndPostData(xml);
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement,
- this.dataTreeCandidates, schemaContext, dataContextTree);
+ this.candidates, schemaContext, dataContextTree);
notificationElement.appendChild(dataChangedNotificationEventElement);
return transformDoc(doc);
}
}
private void addNodeToDataChangeNotificationEventElement(final Document doc,
- final Element dataChangedNotificationEventElement, DataTreeCandidateNode candidateNode,
- YangInstanceIdentifier parentYiid, SchemaContext schemaContext,
- DataSchemaContextTree dataSchemaContextTree) {
+ final Element dataChangedNotificationEventElement, final DataTreeCandidateNode candidateNode,
+ final YangInstanceIdentifier parentYiid, final SchemaContext schemaContext,
+ final DataSchemaContextTree dataSchemaContextTree) {
- Optional<NormalizedNode<?,?>> optionalNormalizedNode = Optional.absent();
+ java.util.Optional<NormalizedNode<?,?>> optionalNormalizedNode = java.util.Optional.empty();
switch (candidateNode.getModificationType()) {
case APPEARED:
case SUBTREE_MODIFIED:
* {@link Operation}
* @return {@link Node} node represented by changed event element.
*/
- private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path,
+ private static Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path,
final Operation operation) {
final Element dataChangeEventElement = doc.createElement("data-change-event");
final Element pathElement = doc.createElement("path");
}
private Node createCreatedChangedDataChangeEventElement(final Document doc,
- YangInstanceIdentifier path, NormalizedNode normalized, final Operation operation,
+ final YangInstanceIdentifier eventPath, final NormalizedNode normalized, final Operation operation,
final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) {
final Element dataChangeEventElement = doc.createElement("data-change-event");
final Element pathElement = doc.createElement("path");
- addPathAsValueToElement(path, pathElement);
+ addPathAsValueToElement(eventPath, pathElement);
dataChangeEventElement.appendChild(pathElement);
final Element operationElement = doc.createElement("operation");
try {
SchemaPath nodePath;
- if ((normalized instanceof MapEntryNode) || (normalized instanceof UnkeyedListEntryNode)) {
- nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath();
+ if (normalized instanceof MapEntryNode || normalized instanceof UnkeyedListEntryNode) {
+ nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath();
} else {
- nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath().getParent();
+ nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath().getParent();
}
final DOMResult domResult = writeNormalizedNode(normalized, schemaContext, nodePath);
final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
* {@link Element}
*/
@SuppressWarnings("rawtypes")
- private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) {
+ private static void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) {
final YangInstanceIdentifier normalizedPath = ControllerContext.getInstance().toXpathRepresentation(path);
final StringBuilder textContent = new StringBuilder();
*/
private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
final QName qualifiedName) {
- final Module module = ControllerContext.getInstance().getGlobalSchema()
- .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision());
+ final Module module = ControllerContext.getInstance().getGlobalSchema().findModule(qualifiedName.getModule())
+ .get();
textContent.append(module.getName());
textContent.append(":");
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onNotification(final DOMNotification notification) {
this.schemaContext = ControllerContext.getInstance().getGlobalSchema();
this.notification = notification;
final Element notificationEventElement = doc.createElementNS(
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
- addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext);
+ addValuesToNotificationEventElement(doc, notificationEventElement);
notificationElement.appendChild(notificationEventElement);
return transformDoc(doc);
}
- private void addValuesToNotificationEventElement(final Document doc, final Element element,
- final DOMNotification notification, final SchemaContext schemaContext) {
- if (notification == null) {
- return;
- }
-
+ private void addValuesToNotificationEventElement(final Document doc, final Element element) {
final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> body =
notification.getBody();
try {
* {@link Notificator} is responsible to create, remove and find
* {@link ListenerAdapter} listener.
*/
-public class Notificator {
+public final class Notificator {
private static Map<String, ListenerAdapter> dataChangeListener = new ConcurrentHashMap<>();
private static Map<String, List<NotificationListenerAdapter>> notificationListenersByStreamName =
* {@link WebSocketServer} is the singleton responsible for starting and stopping the
* web socket server.
*/
-public class WebSocketServer implements Runnable {
+public final class WebSocketServer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
-public class TestRestconfUtils {
+public final class TestRestconfUtils {
private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
try {
Preconditions.checkArgument(yangPath != null, "Path can not be null.");
- Preconditions.checkArgument((!yangPath.isEmpty()), "Path can not be empty.");
+ Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
if (schemaContext == null) {
- return YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(yangPath));
+ return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
} else {
throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
}
} catch (final Exception e) {
- LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
+ LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
}
return schemaContext;
}
@Test
public void stringToInstanceIdentifierTest() throws Exception {
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/instanceidentifier"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/instanceidentifier"));
ControllerContext.getInstance().setGlobalSchema(schemaContext);
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
+import java.util.Optional;
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-
public class TestJsonBodyReader extends AbstractBodyReaderTest {
private final JsonNormalizedNodeBodyReader jsonBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
-
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public TestJsonBodyReader() throws NoSuchFieldException, SecurityException {
this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
public void moduleSubContainerAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode =
schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment");
final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier(
Sets.newHashSet(contAugmentQName));
public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode =
schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
private final JsonNormalizedNodeBodyReader jsonBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public TestJsonBodyReaderMountPoint() throws NoSuchFieldException,
SecurityException {
public static void initialization() throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContext);
final ContainerNode inputNode = (ContainerNode) returnValue.getData();
final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName
.create(inputNode.getNodeType(), "cont"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> contDataNode = inputNode
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> contDataNode = inputNode
.getChild(yangCont.getLastPathArgument());
assertTrue(contDataNode.isPresent());
assertTrue(contDataNode.get() instanceof ContainerNode);
final YangInstanceIdentifier yangleaf = YangInstanceIdentifier.of(QName
.create(inputNode.getNodeType(), "lf"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = ((ContainerNode) contDataNode
- .get()).getChild(yangleaf.getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode =
+ ((ContainerNode) contDataNode.get()).getChild(yangleaf.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue()
.toString()));
.getSchemaContext().getDataChildByName(
dataSchemaNode.getQName());
assertNotNull(mountDataSchemaNode);
- if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
+ if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) {
final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
.getDataChildByName(qualifiedName);
dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
public static void initialization() throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.Assert;
import org.opendaylight.restconf.common.errors.RestconfError;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
private final XmlNormalizedNodeBodyReader xmlBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public TestXmlBodyReader() throws Exception {
this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
testFiles.addAll(TestRestconfUtils.loadFiles("/foo-xml-test/yang"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
public void moduleSubContainerAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode =
schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment");
final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier(
Sets.newHashSet(contAugmentQName));
public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode =
schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
checkNormalizedNodeContext(returnValue);
final ContainerNode contNode = (ContainerNode) returnValue.getData();
final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode.getChild(yangCont
- .getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode
+ .getChild(yangCont.getLastPathArgument());
assertTrue(contDataNodePotential.isPresent());
final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
final YangInstanceIdentifier yangLeaf =
YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(yangLeaf
- .getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(
+ yangLeaf.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString()));
}
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.Assert;
import org.opendaylight.restconf.common.errors.RestconfError;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
private final XmlNormalizedNodeBodyReader xmlBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public TestXmlBodyReaderMountPoint() throws Exception {
this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
public static void initialization() throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContext);
checkNormalizedNodeContext(returnValue);
final ContainerNode contNode = (ContainerNode) returnValue.getData();
final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode.getChild(yangCont
- .getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode
+ .getChild(yangCont.getLastPathArgument());
assertTrue(contDataNodePotential.isPresent());
final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
final YangInstanceIdentifier yangLeaf =
YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(yangLeaf
- .getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(
+ yangLeaf.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString()));
}
.getSchemaContext().getDataChildByName(
dataSchemaNode.getQName());
assertNotNull(mountDataSchemaNode);
- if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
+ if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) {
final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
.getDataChildByName(qualifiedName);
dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
public static void initialization() throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
import java.util.Map;
import org.junit.BeforeClass;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
}
@BeforeClass
- public static void initialize() throws FileNotFoundException, ReactorException {
+ public static void initialize() throws FileNotFoundException {
dataLoad("/cnsn-to-json/simple-data-types");
}
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class RestPutListDataTest {
}
@Before
- public void initialize() throws FileNotFoundException, ReactorException {
+ public void initialize() throws FileNotFoundException {
final ControllerContext controllerContext = ControllerContext.getInstance();
schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
controllerContext.setSchemas(schemaContextTestModule);
final String dataTree = NormalizedNodes.toStringTree(normalizedNodeContext
.getData());
assertTrue(dataTree.contains("lf"));
- assertTrue(dataTree.contains("null"));
+ assertTrue(dataTree.contains("empty"));
}
@Test
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name cont wasn't found under "
+ "Error parsing input: Schema node with name cont was not found under "
+ "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name lst1 wasn't found under "
+ "Error parsing input: Schema node with name lst1 was not found under "
+ "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name lf wasn't found under "
+ "Error parsing input: Schema node with name lf was not found under "
+ "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
assertEquals(3, countExceptions);
public void nnAsYangInstanceIdentifierAugment() throws Exception {
final NormalizedNodeContext normalizedNodeContext = preparNNC();
- final NormalizedNodeXmlBodyWriter xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
final OutputStream output = new ByteArrayOutputStream();
xmlBodyWriter.writeTo(normalizedNodeContext, null, null, null,
public void nnAsYangEmptyToXmlTest() throws Exception {
final String elName = "lfEmpty";
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
- TypeDefinitionAwareCodec.from(BaseTypes.emptyType()).deserialize(null), elName);
+ TypeDefinitionAwareCodec.from(BaseTypes.emptyType()).deserialize(""), elName);
nnToXml(normalizedNodeContext, "<" + elName + "></" + elName + ">");
}
}
private static NormalizedNodeContext prepareNNC(final Object object, final String name) {
- final QName cont = QName.create("basic:module", "2013-12-2", "cont");
- final QName lf = QName.create("basic:module", "2013-12-2", name);
+ final QName cont = QName.create("basic:module", "2013-12-02", "cont");
+ final QName lf = QName.create("basic:module", "2013-12-02", name);
final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont);
}
private static NormalizedNodeContext prepareLeafrefData() {
- final QName cont = QName.create("basic:module", "2013-12-2", "cont");
- final QName lfBoolean = QName.create("basic:module", "2013-12-2", "lfBoolean");
- final QName lfLfref = QName.create("basic:module", "2013-12-2", "lfLfref");
+ final QName cont = QName.create("basic:module", "2013-12-02", "cont");
+ final QName lfBoolean = QName.create("basic:module", "2013-12-02", "lfBoolean");
+ final QName lfLfref = QName.create("basic:module", "2013-12-02", "lfLfref");
final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont);
}
private static NormalizedNodeContext prepareLeafrefNegativeData() {
- final QName cont = QName.create("basic:module", "2013-12-2", "cont");
- final QName lfLfref = QName.create("basic:module", "2013-12-2", "lfLfrefNegative");
+ final QName cont = QName.create("basic:module", "2013-12-02", "cont");
+ final QName lfLfref = QName.create("basic:module", "2013-12-02", "lfLfrefNegative");
final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont);
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contData = Builders
}
private static NormalizedNodeContext prepareIdrefData(final String prefix, final boolean valueAsQName) {
- final QName cont = QName.create("basic:module", "2013-12-2", "cont");
- final QName cont1 = QName.create("basic:module", "2013-12-2", "cont1");
- final QName lf11 = QName.create("basic:module", "2013-12-2", "lf11");
+ final QName cont = QName.create("basic:module", "2013-12-02", "cont");
+ final QName cont1 = QName.create("basic:module", "2013-12-02", "cont1");
+ final QName lf11 = QName.create("basic:module", "2013-12-02", "lf11");
final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont);
Object value = null;
if (valueAsQName) {
- value = QName.create("referenced:module", "2013-12-2", "iden");
+ value = QName.create("referenced:module", "2013-12-02", "iden");
} else {
value = "no qname value";
}
assertTrue(outputString.contains(
"<cont_m2 xmlns=" + '"' + "module:two" + '"' + '>'));
assertTrue(outputString.contains("<lf1_m2>lf1 m2 value</lf1_m2>"));
- assertTrue(outputString.contains("<contB_m2></contB_m2>"));
+ assertTrue(outputString.contains("<contB_m2/>"));
assertTrue(outputString.contains("</cont_m2>"));
// cont m1
assertTrue(outputString.contains(
"<cont_m1 xmlns=" + '"' + "module:one" + '"' + '>'));
- assertTrue(outputString.contains("<contB_m1></contB_m1>"));
+ assertTrue(outputString.contains("<contB_m1/>"));
assertTrue(outputString.contains("<lf1_m1>lf1 m1 value</lf1_m1>"));
assertTrue(outputString.contains("</cont_m1>"));
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class Bug3595Test {
private static ControllerContext controllerContext = ControllerContext.getInstance();
@BeforeClass
- public static void initialize() throws FileNotFoundException, ReactorException {
+ public static void initialize() throws FileNotFoundException {
final SchemaContext schemaContext = TestUtils.loadSchemaContext("/leafref/yang");
Module module = TestUtils.findModule(schemaContext.getModules(), "leafref-module");
assertNotNull(module);
@Test
public void testLeafrefListKeyDeserializtion() {
final YangInstanceIdentifier node1IIexpected = YangInstanceIdentifier.of(CONT_QNAME)
- .node(LST_WITH_LFREF_KEY_QNAME).node(new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+ .node(LST_WITH_LFREF_KEY_QNAME).node(new NodeIdentifierWithPredicates(
LST_WITH_LFREF_KEY_QNAME, LFREF_KEY_QNAME, "node1"));
final InstanceIdentifierContext<?> iiContext =
controllerContext.toInstanceIdentifier("leafref-module:cont/lst-with-lfref-key/node1");
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
final SchemaContext globalContext = TestUtils.loadSchemaContext("/full-versions/yangs");
- assertNull(globalContext.findModuleByName(EXTERNAL_MODULE_NAME, null));
+ assertEquals(0, globalContext.findModules(EXTERNAL_MODULE_NAME).size());
final Set<Module> allModules = globalContext.getModules();
assertNotNull(allModules);
CONTROLLER_CONTEXT.setSchemas(globalContext);
private static YangInstanceIdentifier createInstanceIdentifier() throws URISyntaxException {
final List<PathArgument> pathArguments = new ArrayList<>();
- pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
- pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
+ pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont")));
+ pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont1")));
- final QName qName = new QName(new URI("augment:module"), "lst11");
+ final QName qName = QName.create(new URI("augment:module"), "lst11");
final Map<QName, Object> keyValues = new HashMap<>();
- keyValues.put(new QName(new URI("augment:module"), "keyvalue111"), "value1");
- keyValues.put(new QName(new URI("augment:module"), "keyvalue112"), "value2");
+ keyValues.put(QName.create(new URI("augment:module"), "keyvalue111"), "value1");
+ keyValues.put(QName.create(new URI("augment:module"), "keyvalue112"), "value2");
final NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
new NodeIdentifierWithPredicates(qName, keyValues);
pathArguments.add(nodeIdentifierWithPredicates);
- pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112")));
+ pathArguments.add(new NodeIdentifier(QName.create(new URI("augment:augment:module"), "lf112")));
return YangInstanceIdentifier.create(pathArguments);
}
private static YangInstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException {
final List<PathArgument> pathArguments = new ArrayList<>();
- pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
- pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
- pathArguments.add(new NodeWithValue<>(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1"));
+ pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont")));
+ pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont1")));
+ pathArguments.add(new NodeWithValue<>(QName.create(new URI("augment:module:leaf:list"), "lflst11"),
+ "lflst11_1"));
return YangInstanceIdentifier.create(pathArguments);
}
}
private static NodeIdentifier toIdentifier(final String localName) {
- return new NodeIdentifier(QName.create("urn:nested:module", "2014-06-3", localName));
+ return new NodeIdentifier(QName.create("urn:nested:module", "2014-06-03", localName));
}
private static NodeIdentifierWithPredicates toIdentifier(final String localName, final Map<QName, Object> keys) {
- return new NodeIdentifierWithPredicates(QName.create("urn:nested:module", "2014-06-3", localName),
+ return new NodeIdentifierWithPredicates(QName.create("urn:nested:module", "2014-06-03", localName),
keys);
}
private static NodeWithValue<?> toIdentifier(final String localName, final Object value) {
- return new NodeWithValue<>(QName.create("urn:nested:module", "2014-06-3", localName), value);
+ return new NodeWithValue<>(QName.create("urn:nested:module", "2014-06-03", localName), value);
}
private static UnkeyedListEntryNode nodeDataDepth3Operational() {
private boolean isDone;
private RpcResult<T> result;
- public Builder<T> cancel(final boolean cancel) {
- this.cancel = cancel;
+ public Builder<T> cancel(final boolean newCancel) {
+ this.cancel = newCancel;
return this;
}
- public Builder<T> isCancelled(final boolean isCancelled) {
- this.isCancelled = isCancelled;
+ public Builder<T> isCancelled(final boolean cancelled) {
+ this.isCancelled = cancelled;
return this;
}
- public Builder<T> isDone(final boolean isDone) {
- this.isDone = isDone;
+ public Builder<T> isDone(final boolean done) {
+ this.isDone = done;
return this;
}
- public Builder<T> rpcResult(final RpcResult<T> result) {
- this.result = result;
+ public Builder<T> rpcResult(final RpcResult<T> newResult) {
+ this.result = newResult;
return this;
}
private T result;
private Collection<RpcError> errors;
- public Builder<T> isSuccessful(final boolean isSuccessful) {
- this.isSuccessful = isSuccessful;
+ public Builder<T> isSuccessful(final boolean successful) {
+ this.isSuccessful = successful;
return this;
}
- public Builder<T> result(final T result) {
- this.result = result;
+ public Builder<T> result(final T newResult) {
+ this.result = newResult;
return this;
}
- public Builder<T> errors(final Collection<RpcError> errors) {
- this.errors = errors;
+ public Builder<T> errors(final Collection<RpcError> newErrors) {
+ this.errors = newErrors;
return this;
}
package org.opendaylight.controller.sal.restconf.impl.test;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
}
@Override
- public String getDescription() {
- // TODO Auto-generated method stub
- return null;
+ public Optional<String> getDescription() {
+ return Optional.empty();
}
@Override
- public String getReference() {
- // TODO Auto-generated method stub
- return null;
+ public Optional<String> getReference() {
+ return Optional.empty();
}
@Override
}
@Override
- public String getUnits() {
- // TODO Auto-generated method stub
- return null;
+ public Optional<String> getUnits() {
+ return Optional.empty();
}
@Override
- public Object getDefaultValue() {
- // TODO Auto-generated method stub
- return null;
+ public Optional<? extends Object> getDefaultValue() {
+ return Optional.empty();
}
-
}
}
}
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
- final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName"));
+ final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
final ListenerAdapter listener = Notificator.createListener(path, "streamName", NotificationOutputType.JSON);
listener.setQueryParams(Instant.now(), Optional.empty(), Optional.ofNullable(filter), false);
private static NormalizedNodeContext prepareDomPayload() {
final SchemaContext schema = controllerContext.getGlobalSchema();
- final Module rpcModule = schema.findModuleByName("invoke-rpc-module", null);
+ final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
assertNotNull(rpcModule);
final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
final SchemaContext schemaContext = controllerContext.getGlobalSchema();
- final Module rpcModule = schemaContext.findModuleByName("toaster", null);
+ final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
assertNotNull(rpcModule);
final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
@Test
public void testInvokeRpcWithNoPayloadWithOutput_Success() {
final SchemaContext schema = controllerContext.getGlobalSchema();
- final Module rpcModule = schema.findModuleByName("toaster", null);
+ final Module rpcModule = schema.findModules("toaster").iterator().next();
assertNotNull(rpcModule);
final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getNodeType());
- final Optional<DataContainerChild<?, ?>> mapChild = actualNode.getChild(new NodeIdentifier(INTERFACE_QNAME));
+ final java.util.Optional<DataContainerChild<?, ?>> mapChild = actualNode.getChild(
+ new NodeIdentifier(INTERFACE_QNAME));
assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent());
assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode);
final MapNode mapNode = (MapNode)mapChild.get();
final NodeIdentifierWithPredicates entryNodeID = new NodeIdentifierWithPredicates(
INTERFACE_QNAME, NAME_QNAME, "eth0");
- final Optional<MapEntryNode> entryChild = mapNode.getChild(entryNodeID);
+ final java.util.Optional<MapEntryNode> entryChild = mapNode.getChild(entryNodeID);
assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent());
final MapEntryNode entryNode = entryChild.get();
verifyLeafNode(entryNode, NAME_QNAME, "eth0");
}
@Test(expected = TransactionCommitFailedException.class)
- @SuppressWarnings("checkstyle:IllegalThrows")
+ @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" })
public void testPostFailure() throws Throwable {
doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock"))).when(brokerFacade)
.commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class),
}
void verifyLeafNode(final DataContainerNode<?> parent, final QName leafType, final Object leafValue) {
- final Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
+ final java.util.Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
assertEquals(leafType.toString() + " present", true, leafChild.isPresent());
assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue());
}
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.ArrayList;
-import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
}
private static QName newTestModuleQName(final String localPart) throws Exception {
- final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-09");
- final URI uri = URI.create("test:module");
- return QName.create(uri, revision, localPart);
+ return QName.create(URI.create("test:module"), Revision.of("2014-01-09"), localPart);
}
@Test
assertEquals("module2", qname.getLocalName());
assertEquals("module:2", qname.getNamespace().toString());
- assertEquals("2014-01-02", qname.getFormattedRevision());
+ assertEquals("2014-01-02", qname.getRevision().get().toString());
response = target(uri).request("application/yang.api+json").get();
assertEquals(200, response.getStatus());
final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
assertEquals("module1-behind-mount-point", module.getLocalName());
- assertEquals("2014-02-03", module.getFormattedRevision());
+ assertEquals("2014-02-03", module.getRevision().get().toString());
assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
final NormalizedNode value =
- (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
+ Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build();
when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
fail("Expected RestconfDocumentedException");
"Unexpected child element for parent \"" + element.getLocalName() + "\": "
+ actualElement.getLocalName(), expChild);
- if ((expChild.data == null) || (expChild.data instanceof List)) {
+ if (expChild.data == null || expChild.data instanceof List) {
verifyContainerElement(actualElement, expChild);
} else {
assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
*/
package org.opendaylight.controller.sal.restconf.impl.test;
-public class RestOperationUtils {
+public final class RestOperationUtils {
public static final String JSON = "+json";
public static final String XML = "+xml";
this.broker.setDomDataBroker(this.domDataBroker);
RestconfImpl.getInstance().setBroker(this.broker);
ControllerContext.getInstance()
- .setGlobalSchema(YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/notifications")));
+ .setGlobalSchema(YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications")));
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
- final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName"));
+ final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
Notificator.createListener(path, this.identifier, NotificationOutputType.XML);
}
@Test
public void onNotifiTest() throws Exception {
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
- final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName"));
+ final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
final ListenerAdapter listener = Notificator.createListener(path, this.identifier, NotificationOutputType.XML);
private void binaryKeyTest(final List<Byte> al, final List<Byte> al2) {
- final QName keyDef = QName.create("test:key:binary", "2017-14-08", "b1");
+ final QName keyDef = QName.create("test:key:binary", "2017-08-14", "b1");
final Map<QName, Object> uriKeyValues = new HashMap<>();
uriKeyValues.put(keyDef, al.toArray());
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
-import java.sql.Date;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.transform.stream.StreamResult;
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.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
- public static SchemaContext loadSchemaContext(final String... yangPath)
- throws FileNotFoundException, ReactorException {
+ private TestUtils() {
+
+ }
+
+ public static SchemaContext loadSchemaContext(final String... yangPath) throws FileNotFoundException {
final List<File> files = new ArrayList<>();
for (final String path : yangPath) {
final String pathToFile = TestUtils.class.getResource(path).getPath();
}
}
- return YangParserTestUtils.parseYangSources(files);
+ return YangParserTestUtils.parseYangFiles(files);
}
public static Module findModule(final Set<Module> modules, final String moduleName) {
public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
try {
- final URI u = new URI(uri);
- Date dt = null;
- if (date != null) {
- dt = Date.valueOf(date);
- }
- return QName.create(u, dt, name);
+ return QName.create(new URI(uri), Revision.ofNullable(date), name);
} catch (final URISyntaxException e) {
return null;
}
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
import com.google.common.base.Preconditions;
import java.io.FileNotFoundException;
-import java.text.ParseException;
-import java.util.Date;
import java.util.Set;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
final LogicalDatastoreType datastoreExpected, final DataChangeScope scopeExpected) {
final InstanceIdentifierBuilder iiBuilder = YangInstanceIdentifier.builder();
- iiBuilder.node(QName.create("dummyStreamName"));
+ iiBuilder.node(QName.create("", "dummyStreamName"));
final String datastoreValue = datastore == null ? "CONFIGURATION" : datastore;
final String scopeValue = scope == null ? "BASE" : scope + "";
final UriBuilder uriBuilder = UriBuilder.fromUri("www.whatever.com");
when(mockedUriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
- this.restconf.invokeRpc("sal-remote:create-data-change-event-subscription", prepareDomRpcNode(datastore, scope),
- mockedUriInfo);
+ this.restconf.invokeRpc("sal-remote:create-data-change-event-subscription",
+ prepareDomRpcNode(datastoreValue, scopeValue), mockedUriInfo);
final ListenerAdapter listener =
Notificator.getListenerFor("data-change-event-subscription/opendaylight-inventory:nodes/datastore="
private NormalizedNodeContext prepareDomRpcNode(final String datastore, final String scope) {
final SchemaContext schema = this.controllerContext.getGlobalSchema();
- final Date revDate;
- try {
- revDate = getRevisionFormat().parse("2014-01-14");
- } catch (final ParseException e) {
- throw new IllegalStateException(e);
- }
- final Module rpcSalRemoteModule = schema.findModuleByName("sal-remote", revDate);
+ final Module rpcSalRemoteModule = schema.findModule("sal-remote", Revision.of("2014-01-14")).get();
final Set<RpcDefinition> setRpcs = rpcSalRemoteModule.getRpcs();
final QName rpcQName =
QName.create(rpcSalRemoteModule.getQNameModule(), "create-data-change-event-subscription");
QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "2014-01-14", "path");
final DataSchemaNode pathSchemaNode = rpcInputSchemaNode.getDataChildByName(pathQName);
assertTrue(pathSchemaNode instanceof LeafSchemaNode);
- final LeafNode<Object> pathNode = (Builders.leafBuilder((LeafSchemaNode) pathSchemaNode)
+ final LeafNode<Object> pathNode = Builders.leafBuilder((LeafSchemaNode) pathSchemaNode)
.withValue(YangInstanceIdentifier.builder()
- .node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build())).build();
+ .node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build()).build();
container.withChild(pathNode);
- final AugmentationSchema augmentationSchema = rpcInputSchemaNode.getAvailableAugmentations().iterator().next();
+ final AugmentationSchemaNode augmentationSchema = rpcInputSchemaNode.getAvailableAugmentations().iterator()
+ .next();
Preconditions.checkNotNull(augmentationSchema);
final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> augmentationBuilder =
Builders.augmentationBuilder(augmentationSchema);
- final QName dataStoreQName = QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "datastore");
+ final QName dataStoreQName = QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "datastore");
final DataSchemaNode dsSchemaNode = augmentationSchema.getDataChildByName(dataStoreQName);
assertTrue(dsSchemaNode instanceof LeafSchemaNode);
- final LeafNode<Object> dsNode = (Builders.leafBuilder((LeafSchemaNode) dsSchemaNode)
- .withValue(datastore)).build();
+ final LeafNode<Object> dsNode = Builders.leafBuilder((LeafSchemaNode) dsSchemaNode)
+ .withValue(datastore).build();
augmentationBuilder.withChild(dsNode);
- final QName scopeQName = QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "scope");
+ final QName scopeQName = QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "scope");
final DataSchemaNode scopeSchemaNode = augmentationSchema.getDataChildByName(scopeQName);
assertTrue(scopeSchemaNode instanceof LeafSchemaNode);
- final LeafNode<Object> scopeNode = (Builders.leafBuilder((LeafSchemaNode) scopeSchemaNode)
- .withValue(scope)).build();
+ final LeafNode<Object> scopeNode = Builders.leafBuilder((LeafSchemaNode) scopeSchemaNode)
+ .withValue(scope).build();
augmentationBuilder.withChild(scopeNode);
final QName outputQName =
- QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "notification-output-type");
+ QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "notification-output-type");
final DataSchemaNode outputSchemaNode = augmentationSchema.getDataChildByName(outputQName);
assertTrue(outputSchemaNode instanceof LeafSchemaNode);
final LeafNode<Object> outputNode =
- (Builders.leafBuilder((LeafSchemaNode) outputSchemaNode).withValue("XML")).build();
+ Builders.leafBuilder((LeafSchemaNode) outputSchemaNode).withValue("XML").build();
augmentationBuilder.withChild(outputNode);
container.withChild(augmentationBuilder.build());
when(rpcDef.getPath()).thenReturn(SchemaPath.create(true, rpcQName));
when(rpcDef.getQName()).thenReturn(rpcQName);
- return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null, rpcDef, null, schema),
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcDef, null, schema),
container.build());
}
}
import java.util.Set;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public abstract class YangAndXmlAndDataSchemaLoader {
protected static String searchedDataSchemaName;
protected static String schemaNodePath;
- protected static void dataLoad(final String yangPath) throws FileNotFoundException, ReactorException {
+ protected static void dataLoad(final String yangPath) throws FileNotFoundException {
dataLoad(yangPath, 1, null, null);
}
protected static void dataLoad(final String yangPath, final int modulesNumber, final String moduleName,
- final String dataSchemaName) throws FileNotFoundException, ReactorException {
+ final String dataSchemaName) throws FileNotFoundException {
modules = TestUtils.loadSchemaContext(yangPath).getModules();
assertEquals(modulesNumber, modules.size());
final Module module = TestUtils.resolveModule(moduleName, modules);
package org.opendaylight.netconf.sal.rest.impl;
-import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Collections;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@Before
public void setUp() throws Exception {
this.schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
this.instanceIdentifierDTO = new InstanceIdentifierCodecImpl(null);
ControllerContext.getInstance().setGlobalSchema(this.schemaContext);
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
public void setUp() throws Exception {
dataBroker = getDataBroker();
domDataBroker = getDomBroker();
- SchemaContext sc = YangParserTestUtils.parseYangSource(
+ SchemaContext sc = YangParserTestUtils.parseYangResource(
"/instanceidentifier/yang/instance-identifier-patch-module.yang");
ControllerContext.getInstance().setGlobalSchema(sc);
}
private String lastNotification = null;
- ListenerAdapterTester(YangInstanceIdentifier path, String streamName,
- NotificationOutputTypeGrouping.NotificationOutputType outputType, boolean leafNodesOnly) {
+ ListenerAdapterTester(final YangInstanceIdentifier path, final String streamName,
+ final NotificationOutputTypeGrouping.NotificationOutputType outputType,
+ final boolean leafNodesOnly) {
super(path, streamName, outputType);
setQueryParams(EPOCH, Optional.empty(), Optional.empty(), leafNodesOnly);
}
this.lastNotification = event.getData();
}
- public void assertGot(String json) throws Exception {
+ public void assertGot(final String json) throws Exception {
long start = System.currentTimeMillis();
while (true) {
if (lastNotification != null) {
if (System.currentTimeMillis() - start > 1000) {
throw new Exception("TIMED OUT waiting for notification with " + json);
}
- Thread.currentThread().sleep(200);
+ Thread.currentThread();
+ Thread.sleep(200);
}
LOG.debug("Comparing {} {}", json, lastNotification);
JSONAssert.assertEquals(json, withFakeDate(lastNotification), false);
}
}
- static String withFakeDate(String in) {
+ static String withFakeDate(final String in) {
JSONObject doc = new JSONObject(in);
JSONObject notification = doc.getJSONObject("notification");
if (notification == null) {
return doc.toString();
}
- private String getNotifJson(String path) throws IOException, URISyntaxException {
+ private String getNotifJson(final String path) throws IOException, URISyntaxException {
URL url = getClass().getResource(path);
byte[] bytes = Files.readAllBytes(Paths.get(url.toURI()));
return withFakeDate(new String(bytes, StandardCharsets.UTF_8));
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.net.URI;
-import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yangtools.util.SingletonSet;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
public class NotificationListenerTest {
- private static final QNameModule MODULE;
-
- static {
- try {
- MODULE = QNameModule.create(URI.create("notifi:mod"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2016-11-23"));
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
+ private static final QNameModule MODULE = QNameModule.create(URI.create("notifi:mod"), Revision.of("2016-11-23"));
private SchemaContext schmeaCtx;
description
"Added input parameters to rpc create-data-change-event-subscription";
- revision "2014-7-8" {
+ revision "2014-07-08" {
}
augment "/salrmt:create-data-change-event-subscription/salrmt:input" {
}
}
-}
\ No newline at end of file
+}
prefix "inrpcmod";
- revision 2013-12-3 {
+ revision 2013-12-03 {
}
rpc rpc-noop {
}
-}
\ No newline at end of file
+}
namespace "identity:module";
prefix "idemod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
identity iden {
}
-}
\ No newline at end of file
+}
namespace "identityref:module";
prefix "iderefmod";
-
- import identity-module {prefix idemo; revision-date 2013-12-2;}
-
- revision 2013-12-2 {
+
+ import identity-module {prefix idemo; revision-date 2013-12-02; }
+
+ revision 2013-12-02 {
}
-
+
identity iden_local {
}
-
+
container cont {
container cont1 {
leaf lf11 {
}
}
-}
\ No newline at end of file
+}
module nested-module {
namespace "urn:nested:module";
prefix "nested";
- revision "2014-06-3";
+ revision "2014-06-03";
container depth1-cont {
list depth2-cont1 {
namespace "identity:module";
prefix "idemod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
identity iden {
}
-}
\ No newline at end of file
+}
prefix "iderefmod";
- import identity-module {prefix idemo; revision-date 2013-12-2;}
+ import identity-module {prefix idemo; revision-date 2013-12-02; }
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
container cont {
}
}
-}
\ No newline at end of file
+}
prefix "cntaugmod";
- import main-module {prefix mamo; revision-date 2013-12-2;}
+ import main-module {prefix mamo; revision-date 2013-12-02;}
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
}
}
-}
\ No newline at end of file
+}
namespace "main:module";
prefix "mainmod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
container cont {
prefix "augrefelmo";
- import referenced-elements-module {prefix refelmo; revision-date 2013-12-3;}
+ import referenced-elements-module {prefix refelmo; revision-date 2013-12-03;}
- revision 2013-12-3 {
+ revision 2013-12-03 {
}
augment "/refelmo:cont" {
}
-}
\ No newline at end of file
+}
prefix "refelmo";
- revision 2013-12-3 {
+ revision 2013-12-03 {
}
container cont {
}
-}
\ No newline at end of file
+}
prefix "inidmod";
- revision 2013-12-3 {
+ revision 2013-12-03 {
}
container cont {
}
}
-}
\ No newline at end of file
+}
prefix "basmod";
- import referenced-module {prefix refmo; revision-date 2013-12-2;}
+ import referenced-module {prefix refmo; revision-date 2013-12-02;}
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
container cont {
namespace "referenced:module";
prefix "refmod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
identity iden {
}
-}
\ No newline at end of file
+}
namespace "identity:module";
prefix "idemod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
identity iden {
}
-}
\ No newline at end of file
+}
prefix "iderefmod";
- import identity-module {prefix idemo; revision-date 2013-12-2;}
+ import identity-module {prefix idemo; revision-date 2013-12-02;}
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
container cont {
}
}
-}
\ No newline at end of file
+}
namespace "identity:module";
prefix "idemod";
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
identity iden {
}
-}
\ No newline at end of file
+}
prefix "iderefmod";
- import identity-module {prefix idemo; revision-date 2013-12-2;}
+ import identity-module {prefix idemo; revision-date 2013-12-02;}
import general-module {prefix gmo; revision-date 2013-12-12;}
- revision 2013-12-2 {
+ revision 2013-12-02 {
}
augment "/gmo:cont/gmo:cont1" {
}
}
-}
\ No newline at end of file
+}
package org.opendaylight.restconf.nb.rfc8040;
import java.net.URI;
-import java.text.ParseException;
-import java.util.Date;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
/**
* Base Draft for Restconf project.
throw new UnsupportedOperationException("Util class");
}
- public static final String REVISION = "2017-01-26";
+ public static final Revision REVISION = Revision.of("2017-01-26");
public static final String NAME = "ietf-restconf";
public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-restconf";
+ public static final URI URI_MODULE = URI.create(NAMESPACE);
- public static final QName IETF_RESTCONF_QNAME = QName.create(Rfc8040.RestconfModule.NAMESPACE,
+ public static final QName IETF_RESTCONF_QNAME = QName.create(URI_MODULE,
Rfc8040.RestconfModule.REVISION, Rfc8040.RestconfModule.NAME).intern();
- public static final Date DATE;
-
- static {
- try {
- DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION);
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- public static final URI URI_MODULE = URI.create(NAMESPACE);
-
// RESTCONF
public static final String RESTCONF_GROUPING_SCHEMA_NODE = "restconf";
public static final String RESTCONF_CONTAINER_SCHEMA_NODE = "restconf";
public static final String NAME = "ietf-yang-library";
public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-yang-library";
- public static final String REVISION = "2016-06-21";
-
- public static final Date DATE;
-
- static {
- try {
- DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION);
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
public static final URI URI_MODULE = URI.create(NAMESPACE);
+ public static final Revision REVISION = Revision.of("2016-06-21");
- public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, DATE).intern();
+ public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, REVISION).intern();
public static final String MODULE_SET_ID_LEAF = "module-set-id";
public static final QName MODULE_SET_ID_LEAF_QNAME = QName.create(MODULE_QNAME, MODULE_SET_ID_LEAF).intern();
public static final String NAME = "ietf-restconf-monitoring";
public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-restconf-monitoring";
- public static final String REVISION = "2017-01-26";
+ public static final Revision REVISION = Revision.of("2017-01-26");
public static final String PATH_TO_STREAM_WITHOUT_KEY =
"ietf-restconf-monitoring:restconf-state/streams/stream=";
public static final String PATH_TO_STREAMS = "ietf-restconf-monitoring:restconf-state/streams";
- public static final Date DATE;
-
- static {
- try {
- DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION);
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
public static final URI URI_MODULE = URI.create(NAMESPACE);
- public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, DATE).intern();
+ public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, REVISION).intern();
public static final String CONT_RESTCONF_STATE_NAME = "restconf-state";
public static final QName CONT_RESTCONF_STATE_QNAME = QName.create(MODULE_QNAME, CONT_RESTCONF_STATE_NAME)
import com.google.common.collect.Iterables;
import java.net.URI;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.restconf.common.util.IdentityValuesDTO;
import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RestCodec {
+public final class RestCodec {
private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
private RestCodec() {
}
- public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+ public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
}
final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
Module module = null;
if (mountPoint != null) {
- module = mountPoint.getSchemaContext().findModuleByNamespace(validNamespace).iterator().next();
+ module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
} else {
- module = schemaContext.findModuleByNamespace(validNamespace).iterator().next();
+ module = schemaContext.findModules(validNamespace).iterator().next();
}
if (module == null) {
LOG.info("Module for namespace " + validNamespace + " wasn't found.");
final Iterable<ChoiceSchemaNode> choiceNodes =
Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
- final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
- for (final ChoiceCaseNode caze : Iterables.concat(map)) {
+ final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
+ choice -> choice.getCases().values());
+ for (final CaseSchemaNode caze : Iterables.concat(map)) {
collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
}
}
private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
- return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
- || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
- || (node instanceof AnyXmlSchemaNode);
+ return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
+ || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
+ || node instanceof AnyXmlSchemaNode;
}
}
@Override
protected Module moduleForPrefix(@Nonnull final String prefix) {
- if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) {
- return this.context.findModuleByName(this.defaultPrefix, null);
- } else {
- return this.context.findModuleByName(prefix, null);
- }
+ final String moduleName = prefix.isEmpty() && !defaultPrefix.isEmpty() ? defaultPrefix : prefix;
+ return context.findModules(moduleName).stream().findFirst().orElse(null);
}
@Nonnull
@Nullable
@Override
protected String prefixForNamespace(@Nonnull final URI namespace) {
- final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null);
- return module == null ? null : module.getName();
+ return this.context.findModules(namespace).stream().findFirst().map(Module::getName).orElse(null);
}
-}
\ No newline at end of file
+}
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onGlobalContextUpdated(final SchemaContext context) {
Preconditions.checkNotNull(context);
this.context = null;
this.moduleSetId++;
final Module ietfYangLibraryModule =
- context.findModuleByNamespaceAndRevision(IetfYangLibrary.URI_MODULE, IetfYangLibrary.DATE);
+ context.findModule(IetfYangLibrary.MODULE_QNAME).orElse(null);
NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule,
context, String.valueOf(this.moduleSetId));
putData(normNode);
final Module monitoringModule =
- this.context.findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
+ this.context.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
normNode = RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
putData(normNode);
}
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void update(final DOMTransactionChain transactionChain) {
Preconditions.checkNotNull(transactionChain);
this.transactionChain = transactionChain;
import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
}
while (!foundSchemaNodes.isEmpty()) {
final Object child = foundSchemaNodes.pop();
- if (child instanceof AugmentationSchema) {
- final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
+ if (child instanceof AugmentationSchemaNode) {
+ final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
} else if (child instanceof DataSchemaNode) {
schemaNode = (DataSchemaNode) child;
// find augmentation
if (child.isAugmenting()) {
- final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
+ final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
if (augment != null) {
result.push(augment);
}
}
for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
- for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
+ for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
if (!resultFromRecursion.isEmpty()) {
resultFromRecursion.push(choiceNode);
if (choiceNode.isAugmenting()) {
- final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
+ final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
if (augment != null) {
resultFromRecursion.push(augment);
}
return result;
}
- private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
+ private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
final DataSchemaNode child) {
if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
- for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
+ for (final AugmentationSchemaNode augmentation
+ : ((AugmentationTarget) parent).getAvailableAugmentations()) {
final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
if (childInAugmentation != null) {
return augmentation;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
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.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
LOG.debug("Error parsing xml input", e);
throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE);
+ ErrorTag.MALFORMED_MESSAGE, e);
}
}
? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
// find module according to namespace
- final Module module = pathContext.getSchemaContext().findModuleByNamespace(
- URI.create(namespace)).iterator().next();
+ final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
// initialize codec + set default prefix derived from module name
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
} else {
targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
.concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
- namespace, module.getQNameModule().getFormattedRevision())));
+ namespace,
+ module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import java.util.concurrent.ExecutionException;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import org.opendaylight.restconf.common.schema.SchemaExportContext;
import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
@Provider
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
WebApplicationException {
final RevisionSourceIdentifier sourceId = RevisionSourceIdentifier.create(context.getModule().getName(),
- context.getModule().getQNameModule().getFormattedRevision());
+ context.getModule().getQNameModule().getRevision());
final YangTextSchemaSource yangTextSchemaSource;
try {
- yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).checkedGet();
- } catch (SchemaSourceException e) {
+ yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).get();
+ } catch (InterruptedException | ExecutionException e) {
throw new WebApplicationException("Unable to retrieve source from SourceProvider.", e);
}
yangTextSchemaSource.copyTo(entityStream);
import java.lang.ref.SoftReference;
import java.net.URI;
import java.util.Date;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
* actual {@link SchemaContext}
*/
public SchemaContextRef(final SchemaContext schemaContext) {
- this.schemaContextRef = new SoftReference<SchemaContext>(schemaContext);
+ this.schemaContextRef = new SoftReference<>(schemaContext);
}
/**
* revision of module
* @return {@link Module}
*/
- public Module findModuleByNamespaceAndRevision(final URI namespace, final Date revision) {
- return this.get().findModuleByNamespaceAndRevision(namespace, revision);
+ public Module findModuleByNamespaceAndRevision(final URI namespace, final Optional<Revision> revision) {
+ return this.get().findModule(namespace, revision).orElse(null);
}
-
/**
* Find {@link Module} in {@link SchemaContext} of {@link DOMMountPoint} by
* {@link QName} of {@link Module}.
public Module findModuleInMountPointByQName(final DOMMountPoint mountPoint, final QName moduleQname) {
final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
return schemaContext == null ? null
- : schemaContext.findModuleByName(moduleQname.getLocalName(), moduleQname.getRevision());
+ : schemaContext.findModule(moduleQname.getLocalName(), moduleQname.getRevision()).orElse(null);
}
/**
* revision of module
* @return {@link Module}
*/
- public Module findModuleByNameAndRevision(final String localName, final Date revision) {
- return this.get().findModuleByName(localName, revision);
+ public Module findModuleByNameAndRevision(final String localName, final Optional<Revision> revision) {
+ return this.get().findModule(localName, revision).orElse(null);
}
}
import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.slf4j.Logger;
RestconfError.ErrorTag.DATA_MISSING);
}
- if ((parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL))
+ if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
|| parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
+ final QName type = node.getNodeType();
return Response.status(200)
.entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
- .header("ETag", '"' + node.getNodeType().getModule().getFormattedRevision()
- + node.getNodeType().getLocalName() + '"')
+ .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
+ + type.getLocalName() + '"')
.header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
.build();
}
/**
* Set {@link LogicalDatastoreType} of data for transaction.
*
- * @param configuration
+ * @param datastoreType
* {@link LogicalDatastoreType}
*/
- public void setLogicalDatastoreType(final LogicalDatastoreType configuration) {
- this.configuration = configuration;
+ public void setLogicalDatastoreType(final LogicalDatastoreType datastoreType) {
+ this.configuration = datastoreType;
}
*/
package org.opendaylight.restconf.nb.rfc8040.rests.utils;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
-class ParametersUtil {
+final class ParametersUtil {
private ParametersUtil() {
throw new UnsupportedOperationException("Util class.");
*/
public final class PutDataTransactionUtil {
+ private PutDataTransactionUtil() {
+
+ }
+
/**
* Valid input data with {@link SchemaNode}.
*
if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
final Integer value = Ints.tryParse(depth.get(0));
- if ((value == null)
- || (!((value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH)
- && (value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)))) {
+ if (value == null
+ || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH
+ && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) {
throw new RestconfDocumentedException(
new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
"Invalid depth parameter: " + depth, null,
((ListSchemaNode) childSchema).getKeyDefinition());
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
- final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
- final String nodeVal = ((LeafNode<String>) child).getValue();
+ final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
+ final Object nodeVal = ((LeafNode<?>) child).getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (keys.contains(child.getNodeType())) {
builder.withChild(leafBuilder.build());
} else {
if (trim) {
- if ((defaultVal == null) || !defaultVal.equals(nodeVal)) {
+ if (defaultVal == null || !defaultVal.equals(nodeVal)) {
leafBuilder.withValue(((LeafNode) child).getValue());
builder.withChild(leafBuilder.build());
}
} else {
- if ((defaultVal != null) && defaultVal.equals(nodeVal)) {
+ if (defaultVal != null && defaultVal.equals(nodeVal)) {
leafBuilder.withValue(((LeafNode) child).getValue());
builder.withChild(leafBuilder.build());
}
((ListSchemaNode) childSchema).getKeyDefinition());
builder.withChild(childBuilder.build());
} else if (child instanceof LeafNode) {
- final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
- final String nodeVal = ((LeafNode<String>) child).getValue();
+ final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
+ final Object nodeVal = ((LeafNode<?>) child).getValue();
final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
Builders.leafBuilder((LeafSchemaNode) childSchema);
if (trim) {
- if ((defaultVal == null) || !defaultVal.equals(nodeVal)) {
+ if (defaultVal == null || !defaultVal.equals(nodeVal)) {
leafBuilder.withValue(((LeafNode) child).getValue());
builder.withChild(leafBuilder.build());
}
} else {
- if ((defaultVal != null) && defaultVal.equals(nodeVal)) {
+ if (defaultVal != null && defaultVal.equals(nodeVal)) {
leafBuilder.withValue(((LeafNode) child).getValue());
builder.withChild(leafBuilder.build());
}
}
// if no data exists
- if ((stateDataNode == null) && (configDataNode == null)) {
+ if (stateDataNode == null && configDataNode == null) {
return null;
}
package org.opendaylight.restconf.nb.rfc8040.rests.utils;
import java.net.URI;
-import java.net.URISyntaxException;
-import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
-import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
*/
public final class RestconfDataServiceConstant {
- public static final QName NETCONF_BASE_QNAME;
-
- static {
- try {
- NETCONF_BASE_QNAME = QName.create(
- QNameModule.create(new URI(PutData.NETCONF_BASE), null), PutData.NETCONF_BASE_PAYLOAD_NAME);
- } catch (final URISyntaxException e) {
- final String errMsg = "It wasn't possible to create instance of URI class with " + PutData.NETCONF_BASE
- + " URI";
- throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
- }
- }
+ public static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(PutData.NETCONF_BASE)),
+ PutData.NETCONF_BASE_PAYLOAD_NAME);
private RestconfDataServiceConstant() {
throw new UnsupportedOperationException("Util class.");
* Util class for rpc.
*
*/
-public class RestconfInvokeOperationsUtil {
+public final class RestconfInvokeOperationsUtil {
private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsUtil.class);
} catch (final CancellationException e) {
final String errMsg = "The operation was cancelled while executing.";
LOG.debug("Cancel RpcExecution: " + errMsg, e);
- throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
+ throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
}
}
import com.google.common.collect.ImmutableSet;
import java.net.URI;
-import java.text.ParseException;
-import java.util.Date;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
-import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Constants for streams.
*
*/
public final class RestconfStreamsConstants {
-
- private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsConstants.class);
-
public static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
public static final String DATASTORE_PARAM_NAME = "datastore";
private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
- public static final QNameModule SAL_REMOTE_AUGMENT;
-
- static {
- final Date eventSubscriptionAugRevision;
- try {
- eventSubscriptionAugRevision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08");
- } catch (final ParseException e) {
- final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
- LOG.debug(errMsg);
- throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
- }
- SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, eventSubscriptionAugRevision)
- .intern();
- }
+ public static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
+ Revision.of("2014-07-08")).intern();
public static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier(
ImmutableSet.of(QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
} else {
listeners = pickSpecificListenerByOutput(listeners, NotificationOutputType.XML.getName());
}
- if ((listeners == null) || listeners.isEmpty()) {
+ if (listeners == null || listeners.isEmpty()) {
throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
ErrorTag.UNKNOWN_ELEMENT);
}
public static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
final DataSchemaNode location = ((ContainerSchemaNode) schemaHandler.get()
- .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
+ .findModule(qnameBase.getModule()).get()
.getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
final List<PathArgument> path = new ArrayList<>();
path.add(NodeIdentifier.create(qnameBase));
}
public static Module getMonitoringModule(final SchemaContext schemaContext) {
- final Module monitoringModule =
- schemaContext.findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
- return monitoringModule;
+ return schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
}
/**
* @return enum
*/
private static <T> T parseURIEnum(final Class<T> clazz, final String value) {
- if ((value == null) || value.equals("")) {
+ if (value == null || value.equals("")) {
return null;
}
return ResolveEnumUtil.resolveEnum(clazz, value);
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
}
@Override
- public DataSchemaNode getDataChildByName(final QName name) {
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
for (final DataSchemaNode node : this.children) {
if (node.getQName().equals(name)) {
- return node;
+ return Optional.of(node);
}
}
throw new RestconfDocumentedException(name + " is not in child of " + PATH.getLastComponent());
}
@Override
- public Set<AugmentationSchema> getAvailableAugmentations() {
+ public Set<AugmentationSchemaNode> getAvailableAugmentations() {
return new HashSet<>();
}
return false;
}
- @Override
- public ConstraintDefinition getConstraints() {
- throw new UnsupportedOperationException("Not supported.");
- }
-
@Override
public QName getQName() {
return PATH.getLastComponent();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Not supported.");
}
public boolean isPresenceContainer() {
throw new UnsupportedOperationException("Not supported.");
}
+
+ @Override
+ public Optional<RevisionAwareXPath> getWhenCondition() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Set<NotificationDefinition> getNotifications() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Set<ActionDefinition> getActions() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ throw new UnsupportedOperationException("Not supported.");
+ }
}
import com.google.common.collect.ImmutableSet;
import java.net.URI;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
+import org.opendaylight.yangtools.concepts.SemVer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Deviation;
import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
}
@Override
- public DataSchemaNode getDataChildByName(final QName name) {
- return null;
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
+ return Optional.empty();
}
@Override
return ImmutableSet.of();
}
- @Override
- public String getModuleSourcePath() {
- return null;
- }
-
@Override
public QNameModule getQNameModule() {
return delegate.getQNameModule();
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return delegate.getRevision();
}
}
@Override
- public String getYangVersion() {
+ public YangVersion getYangVersion() {
return delegate.getYangVersion();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
return delegate.getDescription();
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
return delegate.getReference();
}
@Override
- public String getOrganization() {
+ public Optional<String> getOrganization() {
return delegate.getOrganization();
}
@Override
- public String getContact() {
+ public Optional<String> getContact() {
return delegate.getContact();
}
}
@Override
- public Set<AugmentationSchema> getAugmentations() {
+ public Set<AugmentationSchemaNode> getAugmentations() {
return ImmutableSet.of();
}
}
@Override
- public String getSource() {
- return null;
+ public Set<NotificationDefinition> getNotifications() {
+ return ImmutableSet.of();
+ }
+
+ @Override
+ public Optional<SemVer> getSemanticVersion() {
+ return Optional.empty();
}
}
*/
package org.opendaylight.restconf.nb.rfc8040.services.simple.impl;
+import com.google.common.collect.ImmutableList;
+import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
return false;
}
- @Override
- public ConstraintDefinition getConstraints() {
- throw new UnsupportedOperationException("Not supported.");
- }
-
@Override
public QName getQName() {
return path.getLastComponent();
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Not supported operations.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Not supported.");
}
}
@Override
- public String getDefault() {
- throw new UnsupportedOperationException("Not supported.");
+ public Optional<RevisionAwareXPath> getWhenCondition() {
+ return Optional.empty();
}
@Override
- public String getUnits() {
+ public boolean isMandatory() {
throw new UnsupportedOperationException("Not supported.");
}
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ return ImmutableList.of();
+ }
}
package org.opendaylight.restconf.nb.rfc8040.services.simple.impl;
import com.google.common.base.Preconditions;
-import java.util.Date;
+import java.util.Optional;
+import org.opendaylight.yangtools.concepts.SemVer;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.ModuleImport;
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return module.getRevision();
}
public String getPrefix() {
return module.getName();
}
+
+ @Override
+ public Optional<String> getDescription() {
+ return module.getDescription();
+ }
+
+ @Override
+ public Optional<String> getReference() {
+ return module.getReference();
+ }
+
+ @Override
+ public Optional<SemVer> getSemanticVersion() {
+ return module.getSemanticVersion();
+ }
}
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
+import org.opendaylight.yangtools.concepts.SemVer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.common.YangVersion;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Deviation;
*/
final class FakeRestconfModule implements Module {
- static final QNameModule QNAME;
-
- static {
- Date date;
- try {
- date = SimpleDateFormatUtil.getRevisionFormat().parse("2016-06-28");
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), date).intern();
- }
+ static final QNameModule QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"),
+ Revision.of("2016-06-28")).intern();
private final Collection<DataSchemaNode> children;
private final ImmutableSet<ModuleImport> imports;
}
@Override
- public DataSchemaNode getDataChildByName(final QName name) {
+ public Optional<DataSchemaNode> findDataChildByName(final QName name) {
for (final DataSchemaNode node : this.children) {
if (node.getQName().equals(name)) {
- return node;
+ return Optional.of(node);
}
}
throw new RestconfDocumentedException(name + " is not in child of " + FakeRestconfModule.QNAME);
throw new UnsupportedOperationException("Not supported operations.");
}
- @Override
- public String getModuleSourcePath() {
- throw new UnsupportedOperationException("Not supported operations.");
- }
-
@Override
public QNameModule getQNameModule() {
return QNAME;
}
@Override
- public Date getRevision() {
+ public Optional<Revision> getRevision() {
return QNAME.getRevision();
}
}
@Override
- public String getYangVersion() {
- return YangVersion.VERSION_1.toString();
+ public YangVersion getYangVersion() {
+ return YangVersion.VERSION_1;
}
@Override
- public String getDescription() {
+ public Optional<String> getDescription() {
throw new UnsupportedOperationException("Operation not implemented.");
}
@Override
- public String getReference() {
+ public Optional<String> getReference() {
throw new UnsupportedOperationException("Operation not implemented.");
}
@Override
- public String getOrganization() {
+ public Optional<String> getOrganization() {
throw new UnsupportedOperationException("Operation not implemented.");
}
@Override
- public String getContact() {
+ public Optional<String> getContact() {
throw new UnsupportedOperationException("Operation not implemented.");
}
}
@Override
- public Set<AugmentationSchema> getAugmentations() {
+ public Set<AugmentationSchemaNode> getAugmentations() {
throw new UnsupportedOperationException("Operation not implemented.");
}
}
@Override
- public String getSource() {
+ public Optional<SemVer> getSemanticVersion() {
throw new UnsupportedOperationException("Operation not implemented.");
}
}
final SchemaContext context = this.schemaContextHandler.get();
SchemaNode schemaNode = null;
for (final GroupingDefinition groupingDefinition : context
- .findModuleByNamespaceAndRevision(RestconfModule.URI_MODULE, RestconfModule.DATE).getGroupings()) {
+ .findModule(RestconfModule.IETF_RESTCONF_QNAME.getModule()).get().getGroupings()) {
if (groupingDefinition.getQName().equals(RestconfModule.RESTCONF_GROUPING_QNAME)) {
schemaNode = ((ContainerSchemaNode) groupingDefinition
.getDataChildByName(RestconfModule.RESTCONF_CONTAINER_QNAME))
}
}
final YangInstanceIdentifier yangIId = YangInstanceIdentifier.of(
- QName.create(RestconfModule.NAME, RestconfModule.REVISION, RestconfModule.LIB_VER_LEAF_SCHEMA_NODE));
+ QName.create(RestconfModule.IETF_RESTCONF_QNAME, RestconfModule.LIB_VER_LEAF_SCHEMA_NODE));
final InstanceIdentifierContext<? extends SchemaNode> iid =
- new InstanceIdentifierContext<SchemaNode>(yangIId, schemaNode, null, context);
+ new InstanceIdentifierContext<>(yangIId, schemaNode, null, context);
final NormalizedNode<?, ?> data =
Builders.leafBuilder((LeafSchemaNode) schemaNode).withValue(IetfYangLibrary.REVISION).build();
return new NormalizedNodeContext(iid, data);
import org.opendaylight.restconf.nb.rfc8040.services.simple.api.RestconfOperationsService;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
Builders.containerBuilder(fakeCont);
for (final LeafSchemaNode leaf : fakeRpcSchema) {
- containerBuilder.withChild(Builders.leafBuilder(leaf).build());
+ containerBuilder.withChild(Builders.leafBuilder(leaf).withValue(Empty.getInstance()).build());
}
final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
*
*/
@Path("/")
-public class ServicesWrapperImpl implements BaseServicesWrapper, TransactionServicesWrapper, ServiceWrapper {
+public final class ServicesWrapperImpl implements BaseServicesWrapper, TransactionServicesWrapper, ServiceWrapper {
private RestconfDataService delegRestconfDataService;
private RestconfInvokeOperationsService delegRestconfInvokeOpsService;
* {@link MonitoringModule#PATH_TO_STREAM_WITHOUT_KEY} to
* {@link YangInstanceIdentifier}
*/
+ @SuppressWarnings("checkstyle:hiddenField")
public void setCloseVars(final TransactionChainHandler transactionChainHandler,
final SchemaContextHandler schemaHandler) {
this.transactionChainHandler = transactionChainHandler;
* @param localName
* local name
*/
+ @SuppressWarnings("checkstyle:hiddenField")
protected void setLocalNameOfPath(final String localName) {
this.localName = localName;
}
* @param leafNodesOnly
* if true, notifications will contain changes to leaf nodes only
*/
+ @SuppressWarnings("checkstyle:hiddenField")
public void setQueryParams(final Instant start, final Optional<Instant> stop, final Optional<String> filter,
final boolean leafNodesOnly) {
this.start = Preconditions.checkNotNull(start);
this.outputType = Preconditions.checkNotNull(outputType);
this.path = Preconditions.checkNotNull(path);
- Preconditions.checkArgument((streamName != null) && !streamName.isEmpty());
+ Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
this.streamName = streamName;
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
this.change = change;
final String xml = prepareXml();
* @param change
* {@link AsyncDataChangeEvent}
*/
+ @SuppressWarnings("checkstyle:hiddenField")
private void addValuesToDataChangedNotificationEventElement(final Document doc,
final Element dataChangedNotificationEventElement,
final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change,
private void addValuesFromDataToElement(final Document doc, final Set<YangInstanceIdentifier> data,
final Element element, final Operation operation, final SchemaContext schemaContext,
final DataSchemaContextTree dataSchemaContextTree) {
- if ((data == null) || data.isEmpty()) {
+ if (data == null || data.isEmpty()) {
return;
}
- for (final YangInstanceIdentifier path : data) {
- if (!dataSchemaContextTree.getChild(path).isMixin()) {
- final Node node = createDataChangeEventElement(doc, path, operation, schemaContext);
+ for (final YangInstanceIdentifier yiid : data) {
+ if (!dataSchemaContextTree.getChild(yiid).isMixin()) {
+ final Node node = createDataChangeEventElement(doc, yiid, operation, schemaContext);
element.appendChild(node);
}
}
final Set<Entry<YangInstanceIdentifier, NormalizedNode<?, ?>>> data, final Element element,
final Operation operation, final SchemaContext schemaContext,
final DataSchemaContextTree dataSchemaContextTree) {
- if ((data == null) || data.isEmpty()) {
+ if (data == null || data.isEmpty()) {
return;
}
for (final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry : data) {
* schema context
* @return {@link Node} node represented by changed event element.
*/
- private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path,
+ private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier eventPath,
final Operation operation, final SchemaContext schemaContext) {
final Element dataChangeEventElement = doc.createElement("data-change-event");
final Element pathElement = doc.createElement("path");
- addPathAsValueToElement(path, pathElement, schemaContext);
+ addPathAsValueToElement(eventPath, pathElement, schemaContext);
dataChangeEventElement.appendChild(pathElement);
final Element operationElement = doc.createElement("operation");
final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) {
final Element dataChangeEventElement = doc.createElement("data-change-event");
final Element pathElement = doc.createElement("path");
- final YangInstanceIdentifier path = entry.getKey();
- addPathAsValueToElement(path, pathElement, schemaContext);
+ final YangInstanceIdentifier eventPath = entry.getKey();
+ addPathAsValueToElement(eventPath, pathElement, schemaContext);
dataChangeEventElement.appendChild(pathElement);
final Element operationElement = doc.createElement("operation");
try {
SchemaPath nodePath;
final NormalizedNode<?, ?> normalized = entry.getValue();
- if ((normalized instanceof MapEntryNode) || (normalized instanceof UnkeyedListEntryNode)) {
- nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath();
+ if (normalized instanceof MapEntryNode || normalized instanceof UnkeyedListEntryNode) {
+ nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath();
} else {
- nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath().getParent();
+ nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath().getParent();
}
final DOMResult domResult = writeNormalizedNode(normalized, schemaContext, nodePath);
final Node result = doc.importNode(domResult.getNode().getFirstChild(), true);
/**
* Adds path as value to element.
*
- * @param path
+ * @param eventPath
* Path to data in data store.
* @param element
* {@link Element}
* schema context
*/
@SuppressWarnings("rawtypes")
- private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element,
+ private void addPathAsValueToElement(final YangInstanceIdentifier eventPath, final Element element,
final SchemaContext schemaContext) {
final StringBuilder textContent = new StringBuilder();
- for (final PathArgument pathArgument : path.getPathArguments()) {
+ for (final PathArgument pathArgument : eventPath.getPathArguments()) {
if (pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier) {
continue;
}
*/
private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
final QName qualifiedName, final SchemaContext schemaContext) {
- final Module module = schemaContext.findModuleByNamespaceAndRevision(qualifiedName.getNamespace(),
- qualifiedName.getRevision());
+ final Module module = schemaContext.findModule(qualifiedName.getModule()).get();
textContent.append(module.getName());
textContent.append(":");
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onNotification(final DOMNotification notification) {
this.schemaContext = schemaHandler.get();
this.notification = notification;
final Element notificationEventElement = doc.createElementNS(
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream");
- addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext);
+ addValuesToNotificationEventElement(doc, notificationEventElement);
notificationElement.appendChild(notificationEventElement);
return transformDoc(doc);
}
- private void addValuesToNotificationEventElement(final Document doc, final Element element,
- final DOMNotification notification, final SchemaContext schemaContext) {
+ private void addValuesToNotificationEventElement(final Document doc, final Element element) {
if (notification == null) {
return;
}
* {@link Notificator} is responsible to create, remove and find
* {@link ListenerAdapter} listener.
*/
-public class Notificator {
+public final class Notificator {
private static Map<String, ListenerAdapter> dataChangeListener = new ConcurrentHashMap<>();
private static Map<String, List<NotificationListenerAdapter>> notificationListenersByStreamName =
* {@link WebSocketServer} is the singleton responsible for starting and stopping the
* web socket server.
*/
-public class WebSocketServer implements Runnable {
+public final class WebSocketServer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);
import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.Module.ConformanceType;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
addCommonLeafs(module, mapEntryBuilder, ietfYangLibraryModule);
addChildOfModuleBySpecificModuleInternal(
IetfYangLibrary.SPECIFIC_MODULE_SCHEMA_LEAF_QNAME, mapEntryBuilder, IetfYangLibrary.BASE_URI_OF_SCHEMA
- + module.getName() + "/" + module.getQNameModule().getFormattedRevision(),
+ + module.getName() + "/"
+ + module.getQNameModule().getRevision().map(Revision::toString).orElse(null),
ietfYangLibraryModule);
if (!isSubmodule) {
addChildOfModuleBySpecificModuleOfListChild(IetfYangLibrary.SPECIFIC_MODULE_NAMESPACE_LEAF_QNAME,
mapEntryBuilder, module.getNamespace().toString(), ietfYangLibraryModule);
// features - not mandatory
- if ((module.getFeatures() != null) && !module.getFeatures().isEmpty()) {
+ if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
addFeatureLeafList(IetfYangLibrary.SPECIFIC_MODULE_FEATURE_LEAF_LIST_QNAME, mapEntryBuilder,
module.getFeatures(), ietfYangLibraryModule);
}
// deviations - not mandatory
- if ((module.getDeviations() != null) && !module.getDeviations().isEmpty()) {
+ if (module.getDeviations() != null && !module.getDeviations().isEmpty()) {
addDeviationList(module, mapEntryBuilder, ietfYangLibraryModule, context);
addChildOfModuleBySpecificModuleOfListChild(IetfYangLibrary.SPECIFIC_MODULE_CONFORMANCE_LEAF_QNAME,
mapEntryBuilder, ConformanceType.Implement.getName(), ietfYangLibraryModule);
mapEntryBuilder, ConformanceType.Import.getName(), ietfYangLibraryModule);
}
// submodules - not mandatory
- if ((module.getSubmodules() != null) && !module.getSubmodules().isEmpty()) {
+ if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
addSubmodules(module, mapEntryBuilder, ietfYangLibraryModule, context);
}
}
Builders.mapEntryBuilder((ListSchemaNode) deviationsSchema);
final QName lastComponent = deviation.getTargetPath().getLastComponent();
addChildOfModuleBySpecificModule(IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF_QNAME, deviationEntryNode,
- context.findModuleByNamespaceAndRevision(lastComponent.getNamespace(), lastComponent.getRevision())
- .getName(),
+ context.findModule(lastComponent.getModule()).get().getName(),
ietfYangLibraryModule);
addChildOfModuleBySpecificModule(IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF_QNAME, deviationEntryNode,
lastComponent.getRevision(), ietfYangLibraryModule);
addChildOfModuleBySpecificModuleInternal(IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF_QNAME, mapEntryBuilder,
module.getName(), ietfYangLibraryModule);
addChildOfModuleBySpecificModuleInternal(IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF_QNAME, mapEntryBuilder,
- module.getQNameModule().getFormattedRevision(), ietfYangLibraryModule);
+ module.getQNameModule().getRevision().map(Revision::toString).orElse(""), ietfYangLibraryModule);
}
/**
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamEntry =
Builders.mapEntryBuilder((ListSchemaNode) streamListSchema);
- final ListSchemaNode listSchema = ((ListSchemaNode) streamListSchema);
+ final ListSchemaNode listSchema = (ListSchemaNode) streamListSchema;
prepareLeafAndFillEntryBuilder(streamEntry,
listSchema.getDataChildByName(MonitoringModule.LEAF_NAME_STREAM_QNAME),
notificationDefinition.getQName().getLocalName());
- if ((notificationDefinition.getDescription() != null)
- && !notificationDefinition.getDescription().equals("")) {
+
+ final java.util.Optional<String> optDesc = notificationDefinition.getDescription();
+ if (optDesc.isPresent()) {
prepareLeafAndFillEntryBuilder(streamEntry,
- listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME),
- notificationDefinition.getDescription());
+ listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), optDesc.get());
}
prepareLeafAndFillEntryBuilder(streamEntry,
listSchema.getDataChildByName(MonitoringModule.LEAF_REPLAY_SUPP_STREAM_QNAME), true);
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamEntry =
Builders.mapEntryBuilder((ListSchemaNode) streamListSchema);
- final ListSchemaNode listSchema = ((ListSchemaNode) streamListSchema);
+ final ListSchemaNode listSchema = (ListSchemaNode) streamListSchema;
prepareLeafAndFillEntryBuilder(streamEntry,
listSchema.getDataChildByName(MonitoringModule.LEAF_NAME_STREAM_QNAME),
schemaNode.getQName().getLocalName());
- if ((schemaNode.getDescription() != null) && !schemaNode.getDescription().equals("")) {
+
+ final java.util.Optional<String> optDesc = schemaNode.getDescription();
+ if (optDesc.isPresent()) {
prepareLeafAndFillEntryBuilder(streamEntry,
- listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME),
- schemaNode.getDescription());
+ listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), optDesc.get());
}
prepareLeafAndFillEntryBuilder(streamEntry,
listSchema.getDataChildByName(MonitoringModule.LEAF_REPLAY_SUPP_STREAM_QNAME), true);
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class ParserFieldsParameter {
+public final class ParserFieldsParameter {
private static final char COLON = ':';
private static final char SEMICOLON = ';';
private static final char SLASH = '/';
private static final char STARTING_PARENTHESIS = '(';
private static final char CLOSING_PARENTHESIS = ')';
+ private ParserFieldsParameter() {
+
+ }
+
/**
* Parse fields parameter and return complete list of child nodes organized into levels.
* @param identifier identifier context created from request URI
switch (currentChar) {
case COLON :
// new namespace and revision found
- currentQNameModule = context.findModuleByName(
- input.substring(startPosition, currentPosition), null).getQNameModule();
+ currentQNameModule = context.findModules(
+ input.substring(startPosition, currentPosition)).iterator().next().getQNameModule();
currentPosition++;
break;
case STARTING_PARENTHESIS:
@Nonnull final String identifier,
@Nonnull final QNameModule currentQNameModule,
@Nonnull final Set<QName> level) {
- final QName childQName = QName.create(
- currentQNameModule.getNamespace().toString(),
- identifier,
- currentQNameModule.getRevision());
+ final QName childQName = QName.create(currentQNameModule, identifier);
// resolve parent node
final DataSchemaContextNode<?> parentNode = resolveMixinNode(
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
-import java.text.ParseException;
+import java.time.format.DateTimeParseException;
+import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
+import java.util.Map.Entry;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
final QName rpcQName = pathYangInstanceIdentifier.getLastPathArgument().getNodeType();
RpcDefinition def = null;
for (final RpcDefinition rpcDefinition : mountSchemaContext
- .findModuleByNamespaceAndRevision(rpcQName.getNamespace(), rpcQName.getRevision()).getRpcs()) {
+ .findModule(rpcQName.getModule()).get().getRpcs()) {
if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
def = rpcDefinition;
break;
}
final QName rpcQName = deserialize.getLastPathArgument().getNodeType();
RpcDefinition def = null;
- for (final RpcDefinition rpcDefinition
- : schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(),
- rpcQName.getRevision()).getRpcs()) {
+ for (final RpcDefinition rpcDefinition : schemaContext.findModule(rpcQName.getModule()).get().getRpcs()) {
if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
def = rpcDefinition;
break;
}
/**
- * Make a {@link QName} from identifier.
+ * Make a moduleName/Revision pair from identifier.
*
* @param identifier
* path parameter
* @return {@link QName}
*/
- public static QName makeQNameFromIdentifier(final String identifier) {
+ public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
// check if more than one slash is not used as path separator
if (identifier.contains(
String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
ErrorTag.INVALID_VALUE);
}
- final Date moduleRevision;
+ final Revision moduleRevision;
try {
- moduleRevision = SimpleDateFormatUtil.getRevisionFormat().parse(pathArgs.get(1));
- } catch (final ParseException e) {
+ moduleRevision = Revision.of(pathArgs.get(1));
+ } catch (final DateTimeParseException e) {
LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
}
- return QName.create(null, moduleRevision, pathArgs.get(0));
+ return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
}
/**
final Iterator<String> componentIter = pathComponents.iterator();
if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
- final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
- final Module module = schemaContext.findModuleByName(moduleName, revision);
-
+ final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
+ final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
return new SchemaExportContext(schemaContext, module, sourceProvider);
} else {
final StringBuilder pathBuilder = new StringBuilder();
final InstanceIdentifierContext<?> point = ParserIdentifier
.toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
- final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
- final Module module = point.getMountPoint().getSchemaContext().findModuleByName(moduleName, revision);
+ final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
+ final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
+ .orElse(null);
return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
}
}
// this is the last identifier (input is consumed) or end of identifier (slash)
if (allCharsConsumed(variables)
- || (currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH)) {
+ || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) {
prepareIdentifier(qname, path, variables);
if (variables.getCurrent() == null) {
path.add(NodeIdentifier.create(qname));
final MainVarsWrapper variables) {
final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode();
- checkValid((dataSchemaNode != null), "Data schema node is null", variables.getData(), variables.getOffset());
+ checkValid(dataSchemaNode != null, "Data schema node is null", variables.getData(), variables.getOffset());
final Iterator<QName> keys = ((ListSchemaNode) dataSchemaNode).getKeyDefinition().iterator();
final ImmutableMap.Builder<QName, Object> values = ImmutableMap.builder();
skipCurrentChar(variables);
// read key value separated by comma
- while (keys.hasNext() && !allCharsConsumed(variables) && (currentChar(variables.getOffset(),
- variables.getData()) != RestconfConstants.SLASH)) {
+ while (keys.hasNext() && !allCharsConsumed(variables) && currentChar(variables.getOffset(),
+ variables.getData()) != RestconfConstants.SLASH) {
// empty key value
if (currentChar(variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) {
// skip comma
- if (keys.hasNext() && !allCharsConsumed(variables) && (currentChar(
- variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA)) {
+ if (keys.hasNext() && !allCharsConsumed(variables) && currentChar(
+ variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) {
skipCurrentChar(variables);
}
}
// the last key is considered to be empty
if (keys.hasNext()) {
if (allCharsConsumed(variables)
- || (currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH)) {
+ || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) {
values.put(keys.next(), ParserBuilderConstants.Deserializer.EMPTY_STRING);
}
final Codec<Object, Object> codec = RestCodec.from(typedef, null, vars.getSchemaContext());
decoded = codec.deserialize(value);
if (decoded == null) {
- if ((baseType instanceof IdentityrefTypeDefinition)) {
+ if (baseType instanceof IdentityrefTypeDefinition) {
decoded = toQName(value, schemaNode, vars.getSchemaContext());
}
}
final SchemaContext schemaContext) {
final String moduleName = toModuleName(value);
final String nodeName = toNodeName(value);
- final Module module = schemaContext.findModuleByName(moduleName, null);
+ final Module module = schemaContext.findModules(moduleName).iterator().next();
for (final IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
final QName qName = identitySchemaNode.getQName();
if (qName.getLocalName().equals(nodeName)) {
variables.getOffset());
localName = nextIdentifierFromNextSequence(ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
- if (!allCharsConsumed(variables) && (currentChar(
- variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL)) {
+ if (!allCharsConsumed(variables) && currentChar(
+ variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL) {
return getQNameOfDataSchemaNode(localName, variables);
} else {
final Module module = moduleForPrefix(prefix, variables.getSchemaContext());
DataSchemaContextNode<?> current = variables.getCurrent();
if (current == null) {
for (final RpcDefinition rpcDefinition : variables.getSchemaContext()
- .findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision()).getRpcs()) {
+ .findModule(qname.getModule()).orElse(null).getRpcs()) {
if (rpcDefinition.getQName().getLocalName().equals(qname.getLocalName())) {
return null;
}
}
private static Module moduleForPrefix(final String prefix, final SchemaContext schemaContext) {
- return schemaContext.findModuleByName(prefix, null);
+ return schemaContext.findModules(prefix).stream().findFirst().orElse(null);
}
private static void validArg(final MainVarsWrapper variables) {
package org.opendaylight.restconf.nb.rfc8040.utils.parser;
import com.google.common.base.Preconditions;
-import java.net.URI;
import java.util.Iterator;
import java.util.Map.Entry;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
* @return {@link String}
*/
private static String prefixForNamespace(final QName qname, final SchemaContext schemaContext) {
- final URI namespace = qname.getNamespace();
- Preconditions.checkArgument(namespace != null, "Failed to map QName {}", qname);
- final Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, qname.getRevision());
+ final Module module = schemaContext.findModule(qname.getModule()).orElse(null);
return module.getName();
}
*/
package org.opendaylight.restconf.nb.rfc8040.utils.validations;
-import java.text.ParseException;
+import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Iterator;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
/**
* Util class for validations.
* iterator
* @return {@link Date}
*/
- public static Date validateAndGetRevision(final Iterator<String> revisionDate) {
+ public static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
RestconfValidationUtils.checkDocumentedError(revisionDate.hasNext(), ErrorType.PROTOCOL,
ErrorTag.INVALID_VALUE, "Revision date must be supplied.");
try {
- return SimpleDateFormatUtil.getRevisionFormat().parse(revisionDate.next());
- } catch (final ParseException e) {
+ return Revision.of(revisionDate.next());
+ } catch (final DateTimeParseException e) {
throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
}
}
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
-public class TestRestconfUtils {
+public final class TestRestconfUtils {
private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
try {
Preconditions.checkArgument(yangPath != null, "Path can not be null.");
- Preconditions.checkArgument((!yangPath.isEmpty()), "Path can not be empty.");
+ Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty.");
if (schemaContext == null) {
- return YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(yangPath));
+ return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath));
} else {
throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context.");
}
} catch (final Exception e) {
- LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
+ LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e);
}
return schemaContext;
}
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
-import java.sql.Date;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.transform.stream.StreamResult;
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.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
+ private TestUtils() {
+
+ }
+
public static SchemaContext loadSchemaContext(final String... yangPath)
- throws FileNotFoundException, ReactorException {
+ throws FileNotFoundException {
final List<File> files = new ArrayList<>();
for (final String path : yangPath) {
final String pathToFile = TestUtils.class.getResource(path).getPath();
}
}
- return YangParserTestUtils.parseYangSources(files);
+ return YangParserTestUtils.parseYangFiles(files);
}
public static Module findModule(final Set<Module> modules, final String moduleName) {
public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
try {
final URI u = new URI(uri);
- Date dt = null;
- if (date != null) {
- dt = Date.valueOf(date);
- }
- return QName.create(u, dt, name);
+ return QName.create(u, Revision.ofNullable(date), name);
} catch (final URISyntaxException e) {
return null;
}
this.schemaContextHandler = new SchemaContextHandler(txHandler);
this.schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_ACTUAL_SCHEMA_CONTEXT));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_ACTUAL_SCHEMA_CONTEXT));
this.schemaContextHandler.onGlobalContextUpdated(this.schemaContext);
}
public void onGlobalContextUpdateTest() throws Exception {
// create new SchemaContext and update SchemaContextHandler
final SchemaContext newSchemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT));
this.schemaContextHandler.onGlobalContextUpdated(newSchemaContext);
assertNotEquals("SchemaContextHandler should not has reference to old SchemaContext",
package org.opendaylight.restconf.nb.rfc8040.jersey.providers;
-import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Collections;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
package org.opendaylight.restconf.nb.rfc8040.jersey.providers;
-import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.Assert;
import org.opendaylight.restconf.nb.rfc8040.jersey.providers.test.XmlBodyReaderTest;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
private final XmlNormalizedNodeBodyReader xmlBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public XmlBodyReaderMountPointTest() throws Exception {
this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
public static void initialization() throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
final DOMMountPointService mountPointService = mock(DOMMountPointService.class);
final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
checkNormalizedNodeContext(returnValue);
final ContainerNode contNode = (ContainerNode) returnValue.getData();
final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode.getChild(
- yangCont.getLastPathArgument());
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode
+ .getChild(yangCont.getLastPathArgument());
assertTrue(contDataNodePotential.isPresent());
final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
final YangInstanceIdentifier yangLeaf =
YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
- final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(
+ final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(
yangLeaf.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString()));
.getSchemaContext().getDataChildByName(
dataSchemaNode.getQName());
assertNotNull(mountDataSchemaNode);
- if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
+ if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) {
final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
.getDataChildByName(qualifiedName);
dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
+import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
import org.opendaylight.restconf.nb.rfc8040.jersey.providers.JsonNormalizedNodeBodyReader;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
private final JsonNormalizedNodeBodyReader jsonBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public JsonBodyReaderTest() throws Exception {
this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
throws NoSuchFieldException, SecurityException, FileNotFoundException, SourceException, ReactorException {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/modules"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
+ SchemaContextHandler.setActualSchemaContext(schemaContext);
}
@Test
public void moduleSubContainerAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode = schemaContext
.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment");
final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier(
Sets.newHashSet(contAugmentQName));
public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode = schemaContext
.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
import java.io.File;
import java.io.InputStream;
import java.net.URI;
-import java.text.ParseException;
import java.util.Collection;
import javax.ws.rs.core.MediaType;
import org.junit.Assert;
import org.opendaylight.restconf.nb.rfc8040.jersey.providers.XmlNormalizedNodeBodyReader;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
private final XmlNormalizedNodeBodyReader xmlBodyReader;
private static SchemaContext schemaContext;
- private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
-
- private static QNameModule initializeInstanceIdentifierModule() {
- try {
- return QNameModule.create(URI.create("instance:identifier:module"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
- } catch (final ParseException e) {
- throw new Error(e);
- }
- }
+ private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
+ URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
public XmlBodyReaderTest() throws Exception {
this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/modules"));
testFiles.addAll(TestRestconfUtils.loadFiles("/foo-xml-test/yang"));
- schemaContext = YangParserTestUtils.parseYangSources(testFiles);
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
SchemaContextHandler.setActualSchemaContext(schemaContext);
}
public void moduleSubContainerAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode = schemaContext
.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment");
final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier(
Sets.newHashSet(contAugmentQName));
public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception {
final DataSchemaNode dataSchemaNode = schemaContext
.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
- final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next();
+ final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next();
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getNodeType());
- final Optional<DataContainerChild<?, ?>> mapChild = actualNode.getChild(new NodeIdentifier(INTERFACE_QNAME));
+ final java.util.Optional<DataContainerChild<?, ?>> mapChild = actualNode.getChild(
+ new NodeIdentifier(INTERFACE_QNAME));
assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent());
assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode);
final MapNode mapNode = (MapNode)mapChild.get();
final NodeIdentifierWithPredicates entryNodeID = new NodeIdentifierWithPredicates(
INTERFACE_QNAME, NAME_QNAME, "eth0");
- final Optional<MapEntryNode> entryChild = mapNode.getChild(entryNodeID);
+ final java.util.Optional<MapEntryNode> entryChild = mapNode.getChild(entryNodeID);
assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent());
final MapEntryNode entryNode = entryChild.get();
verifyLeafNode(entryNode, NAME_QNAME, "eth0");
}
@Test(expected = TransactionCommitFailedException.class)
- @SuppressWarnings("checkstyle:IllegalThrows")
+ @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" })
public void testPostFailure() throws Throwable {
doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock")))
.when(mockReadWriteTx).submit();
}
void verifyLeafNode(final DataContainerNode<?> parent, final QName leafType, final Object leafValue) {
- final Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
+ final java.util.Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
assertEquals(leafType.toString() + " present", true, leafChild.isPresent());
assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue());
}
.build();
this.contextRef = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
this.schemaNode = DataSchemaContextTree.from(this.contextRef.get()).getChild(this.iidBase).getDataSchemaNode();
final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class);
@Test
public void testPutDataWithMountPoint() {
final DOMDataBroker dataBroker = Mockito.mock(DOMDataBroker.class);
- final DOMMountPoint mountPoint = Mockito.mock(DOMMountPoint.class);
doReturn(Optional.of(dataBroker)).when(mountPoint).getService(DOMDataBroker.class);
doReturn(this.transactionChainHandler.get()).when(dataBroker)
.createTransactionChain(RestConnectorProvider.TRANSACTION_CHAIN_LISTENER);
final String errorMessage = status.getEditCollection().get(2).getEditErrors().get(0).getErrorMessage();
assertEquals("Data does not exist", errorMessage);
}
-}
\ No newline at end of file
+}
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
final SchemaContextRef contextRef = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class);
final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class);
Mockito.when(txHandler.get()).thenReturn(domTx);
private NormalizedNodeContext prepNNC(final NormalizedNode result) {
final InstanceIdentifierContext context = Mockito.mock(InstanceIdentifierContext.class);
final RpcDefinition schemaNode = Mockito.mock(RpcDefinition.class);
- final QName qname = QName.create("invoke:rpc:module", "2013-12-3", "rpcTest");
+ final QName qname = QName.create("invoke:rpc:module", "2013-12-03", "rpcTest");
final SchemaPath schemaPath = SchemaPath.create(true, qname);
Mockito.when(schemaNode.getPath()).thenReturn(schemaPath);
Mockito.when(schemaNode.getQName()).thenReturn(qname);
Mockito.when(uriInfo.getBaseUri()).thenReturn(baseUriBuilder.build());
Mockito.when(uriInfo.getBaseUriBuilder()).thenReturn(baseUriBuilder);
this.schemaHandler.onGlobalContextUpdated(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/notifications")));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications")));
}
private static class LocalUriInfo extends SimpleUriInfo {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.refSchemaCtx = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
}
@Test
private NormalizedNodeContext prepareDomPayload(final String rpcName, final String inputOutput,
final String toasterValue, final String inputOutputName) {
final SchemaContext schema = this.refSchemaCtx.get();
- final Module rpcModule = schema.findModuleByName("sal-remote", null);
- assertNotNull(rpcModule);
+ final Module rpcModule = schema.findModules("sal-remote").iterator().next();
final QName rpcQName = QName.create(rpcModule.getQNameModule(), rpcName);
final QName rpcInputQName = QName.create(rpcModule.getQNameModule(), inputOutput);
final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
} else {
o = toasterValue;
}
- final LeafNode<Object> lfNode = (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode)
- .withValue(o)).build();
+ final LeafNode<Object> lfNode = Builders.leafBuilder((LeafSchemaNode) lfSchemaNode)
+ .withValue(o).build();
container.withChild(lfNode);
return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema),
private DOMDataReadWriteTransaction rwTransaction;
private SchemaContextRef refSchemaCtx;
+ private YangInstanceIdentifier instanceIdContainer;
private YangInstanceIdentifier instanceIdCreateAndDelete;
private YangInstanceIdentifier instanceIdMerge;
private ContainerNode buildBaseContainerForTests;
PatchDataTransactionUtilTest.broker.set(RestConnectorProvider.class, mock(DOMDataBroker.class));
this.refSchemaCtx = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox");
final QName containerPlayerQName = QName.create(baseQName, "player");
final QName leafGapQName = QName.create(baseQName, "gap");
final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeWithKey =
new YangInstanceIdentifier.NodeIdentifierWithPredicates(listArtistQName, leafNameQName, "name of artist");
- /* instance identifier for accessing leaf node "gap" */
- this.instanceIdCreateAndDelete = YangInstanceIdentifier.builder()
+ /* instance identifier for accessing container node "player" */
+ this.instanceIdContainer = YangInstanceIdentifier.builder()
.node(baseQName)
.node(containerPlayerQName)
- .node(leafGapQName)
.build();
+ /* instance identifier for accessing leaf node "gap" */
+ this.instanceIdCreateAndDelete = instanceIdContainer.node(leafGapQName);
+
/* values that are used for creating leaf for testPatchDataCreateAndDelete test */
final LeafNode<?> buildGapLeaf = Builders.leafBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafGapQName))
@Test
public void testPatchDataCreateAndDelete() throws Exception {
- doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
- .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceIdContainer);
+ doReturn(Futures.immediateCheckedFuture(true))
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
final PatchEntity entityCreate =
- new PatchEntity("edit1", CREATE, this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
+ new PatchEntity("edit1", CREATE, this.instanceIdContainer, this.buildBaseContainerForTests);
final PatchEntity entityDelete =
new PatchEntity("edit2", DELETE, this.targetNodeForCreateAndDelete);
final List<PatchEntity> entities = new ArrayList<>();
PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
for (final PatchStatusEntity entity : patchStatusContext.getEditCollection()) {
- assertTrue(entity.isOk());
+ assertTrue("Edit " + entity.getEditId() + " failed", entity.isOk());
}
assertTrue(patchStatusContext.isOk());
}
.when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
final PatchEntity entityMerge =
- new PatchEntity("edit1", MERGE, this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
+ new PatchEntity("edit1", MERGE, this.instanceIdContainer, this.buildBaseContainerForTests);
final List<PatchEntity> entities = new ArrayList<>();
entities.add(entityMerge);
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.refSchemaCtx = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
this.schema = this.refSchemaCtx.get();
final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox");
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.refSchemaCtx = new SchemaContextRef(
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
this.schema = this.refSchemaCtx.get();
final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox");
@Test
public void restImplTest() throws Exception {
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/impl"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/impl"));
final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class);
final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class);
package org.opendaylight.restconf.nb.rfc8040.services.simple.impl;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableSet;
import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
- this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules"));
+ this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules"));
final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class);
final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class);
this.domMountPointServiceHandler = new DOMMountPointServiceHandler(this.domMountPointService);
- final QNameModule module1 = QNameModule.create(new URI("module:1"), null);
- final QNameModule module2 = QNameModule.create(new URI("module:2"), null);
+ final QNameModule module1 = QNameModule.create(URI.create("module:1"));
+ final QNameModule module2 = QNameModule.create(URI.create("module:2"));
this.listOfRpcsNames = ImmutableSet.of(QName.create(module1, "dummy-rpc1-module1"),
QName.create(module1, "dummy-rpc2-module1"), QName.create(module2, "dummy-rpc1-module2"),
assertEquals(4, data.getValue().size());
for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
- assertNull(child.getValue());
+ assertEquals(Empty.getInstance(), child.getValue());
final QName qname = child.getNodeType().withoutRevision();
assertTrue(this.listOfRpcsNames.contains(qname));
import org.opendaylight.restconf.nb.rfc8040.services.simple.api.RestconfSchemaService;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
- this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules"));
+ this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules"));
this.schemaContextBehindMountPoint = YangParserTestUtils
- .parseYangSources(TestRestconfUtils.loadFiles("/modules/modules-behind-mount-point"));
+ .parseYangFiles(TestRestconfUtils.loadFiles("/modules/modules-behind-mount-point"));
this.schemaContextWithMountPoints =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules/mount-points"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules/mount-points"));
// create and register mount points
this.mountPoint = SimpleDOMMountPoint.create(
assertNotNull("Existing module should be found", module);
assertEquals("Not expected module name", "module1", module.getName());
- assertEquals("Not expected module revision", "2014-01-01",
- SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()));
+ assertEquals("Not expected module revision", Revision.ofNullable("2014-01-01"), module.getRevision());
assertEquals("Not expected module namespace", "module:1", module.getNamespace().toString());
}
assertNotNull("Existing module should be found", module);
assertEquals("Not expected module name", "module1-behind-mount-point", module.getName());
- assertEquals("Not expected module revision", "2014-02-03",
- SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()));
+ assertEquals("Not expected module revision", Revision.ofNullable("2014-02-03"), module.getRevision());
assertEquals("Not expected module namespace", "module:1:behind:mount:point", module.getNamespace().toString());
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.net.URI;
-import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yangtools.util.SingletonSet;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
public class NotificationListenerTest {
- private static final QNameModule MODULE;
-
- static {
- try {
- MODULE = QNameModule.create(URI.create("notifi:mod"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2016-11-23"));
- } catch (final ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
+ private static final QNameModule MODULE = QNameModule.create(URI.create("notifi:mod"), Revision.of("2016-11-23"));
private SchemaContext schmeaCtx;
import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@BeforeClass
public static void loadTestSchemaContextAndModules() throws Exception {
schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules/restconf-module-testing"));
- schemaContextMonitoring = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing"));
+ schemaContextMonitoring = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules"));
modules = schemaContextMonitoring.getModules();
modulesRest = YangParserTestUtils
- .parseYangSources(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")).getModules();
+ .parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")).getModules();
}
@Before
when(this.leafDescription.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.DESCRIPTION));
when(this.leafReplaySupport.getQName()).thenReturn(
QName.create("", RestconfMappingNodeConstants.REPLAY_SUPPORT));
- when(this.leafReplayLog.getQName()).thenReturn(QName.create(RestconfMappingNodeConstants.REPLAY_LOG));
+ when(this.leafReplayLog.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.REPLAY_LOG));
when(this.leafEvents.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.EVENTS));
}
@Test
public void restconfMappingNodeTest() {
// write modules into list module in Restconf
- final Module ietfYangLibMod =
- schemaContext.findModuleByNamespaceAndRevision(IetfYangLibrary.URI_MODULE, IetfYangLibrary.DATE);
- final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> modules =
+ final Module ietfYangLibMod = schemaContext.findModule(IetfYangLibrary.MODULE_QNAME).get();
+ final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> mods =
RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(RestconfMappingNodeUtilTest.modules,
ietfYangLibMod, schemaContext, "1");
// verify loaded modules
- verifyLoadedModules((ContainerNode) modules);
+ verifyLoadedModules((ContainerNode) mods);
}
@Test
public void restconfStateCapabilitesTest() {
- final Module monitoringModule = schemaContextMonitoring
- .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
+ final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).get();
final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
assertNotNull(normNode);
final Instant start = Instant.now();
final String outputType = "XML";
final URI uri = new URI("uri");
- final Module monitoringModule = schemaContextMonitoring
- .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
+ final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
final boolean exist = true;
final Map<QName, Object> map =
final Instant start = Instant.now();
final String outputType = "JSON";
final URI uri = new URI("uri");
- final Module monitoringModule = schemaContextMonitoring
- .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
+ final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
final boolean exist = true;
final Map<QName, Object> map = prepareMap("notifi", uri, start, outputType);
map.put(MonitoringModule.LEAF_DESCR_STREAM_QNAME, "Notifi");
- final QName notifiQName = QName.create("urn:nested:module", "2014-06-3", "notifi");
+ final QName notifiQName = QName.create("urn:nested:module", "2014-06-03", "notifi");
final NormalizedNode<?, ?> mappedData =
RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(notifiQName,
schemaContextMonitoring.getNotifications(), start, outputType, uri, monitoringModule, exist);
final String revision = loadedModules.get(name);
assertNotNull("Expected module not found", revision);
- assertEquals("Not correct revision of loaded module",
- SimpleDateFormatUtil.getRevisionFormat().format(m.getRevision()), revision);
+ assertEquals("Incorrect revision of loaded module", Revision.ofNullable(revision), m.getRevision());
loadedModules.remove(name);
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import java.io.FileNotFoundException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
private SchemaContext schemaContext;
@Before
- public void init() throws Exception {
- this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser"));
+ public void init() throws FileNotFoundException {
+ this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser"));
}
/**
import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/jukebox"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/jukebox"));
final QNameModule qNameModule = QNameModule.create(URI.create("http://example.com/ns/example-jukebox"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2015-04-04"));
+ Revision.of("2015-04-04"));
this.jukeboxQName = QName.create(qNameModule, "jukebox");
this.playerQName = QName.create(qNameModule, "player");
this.augmentedLibraryQName = QName.create(
QNameModule.create(
URI.create("http://example.com/ns/augmented-jukebox"),
- SimpleDateFormatUtil.getRevisionFormat().parse("2016-05-05")),
+ Revision.of("2016-05-05")),
"augmented-library");
this.albumQName = QName.create(qNameModule, "album");
this.nameQName = QName.create(qNameModule, "name");
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.Maps;
+import java.util.Map.Entry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
- this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/parser-identifier"));
+ this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/parser-identifier"));
this.schemaContextOnMountPoint =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/parser-identifier"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/parser-identifier"));
// create and register mount point
this.mountPoint = SimpleDOMMountPoint.create(
*/
@Test
public void makeQNameFromIdentifierTest() {
- final QName qName = ParserIdentifier.makeQNameFromIdentifier(TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION);
+ final Entry<String, Revision> qName = ParserIdentifier.makeQNameFromIdentifier(
+ TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION);
assertNotNull("QName should be created", qName);
- assertEquals("Returned not expected module name",
- TEST_MODULE_NAME, qName.getLocalName());
- assertEquals("Returned not expected module revision",
- TEST_MODULE_REVISION, qName.getFormattedRevision());
+ assertEquals("Returned not expected module name", TEST_MODULE_NAME, qName.getKey());
+ assertEquals("Returned not expected module revision", Revision.of(TEST_MODULE_REVISION), qName.getValue());
}
/**
*/
@Test
public void makeQNameFromIdentifierMountTest() {
- final QName qName = ParserIdentifier.makeQNameFromIdentifier(
+ final Entry<String, Revision> qName = ParserIdentifier.makeQNameFromIdentifier(
MOUNT_POINT_IDENT
+ "/"
+ TEST_MODULE_NAME
+ TEST_MODULE_REVISION);
assertNotNull("QName should be created", qName);
- assertEquals("Returned not expected module name",
- TEST_MODULE_NAME, qName.getLocalName());
- assertEquals("Returned not expected module revision",
- TEST_MODULE_REVISION, qName.getFormattedRevision());
+ assertEquals("Returned not expected module name", TEST_MODULE_NAME, qName.getKey());
+ assertEquals("Returned not expected module revision", Revision.of(TEST_MODULE_REVISION), qName.getValue());
}
/**
assertEquals("Returned not expected module name",
TEST_MODULE_NAME, module.getName());
assertEquals("Returned not expected module revision",
- TEST_MODULE_REVISION, SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()));
+ Revision.ofNullable(TEST_MODULE_REVISION), module.getRevision());
assertEquals("Returned not expected module namespace",
TEST_MODULE_NAMESPACE, module.getNamespace().toString());
}
assertEquals("Returned not expected module name",
TEST_MODULE_NAME, module.getName());
assertEquals("Returned not expected module revision",
- TEST_MODULE_REVISION, SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()));
+ Revision.ofNullable(TEST_MODULE_REVISION), module.getRevision());
assertEquals("Returned not expected module namespace",
TEST_MODULE_NAMESPACE, module.getNamespace().toString());
}
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
+import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
private SchemaContext schemaContext;
@Before
- public void init() throws Exception {
+ public void init() throws FileNotFoundException {
this.schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
}
/**
@Before
public void init() throws Exception {
this.schemaContext =
- YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/serializer"));
+ YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/serializer"));
}
/**
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError;
+import org.opendaylight.yangtools.yang.common.Revision;
/**
* Unit test for {@link RestconfValidation}.
*/
@Test
public void validateAndGetRevisionTest() {
- final Date revision = RestconfValidation.validateAndGetRevision(REVISIONS.iterator());
+ final Revision revision = RestconfValidation.validateAndGetRevision(REVISIONS.iterator());
assertNotNull("Correct module revision should be validated", revision);
-
- final Calendar calendar = Calendar.getInstance();
- calendar.setTime(revision);
-
- assertEquals(2014, calendar.get(Calendar.YEAR));
- assertEquals(0, calendar.get(Calendar.MONTH));
- assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH));
+ assertEquals(Revision.of("2014-01-01"), revision);
}
/**
prefix "inrpcmod";
- revision 2013-12-3 {
+ revision 2013-12-03 {
}
rpc rpc-noop {
}
-}
\ No newline at end of file
+}
module nested-module {
namespace "urn:nested:module";
prefix "nested";
- revision "2014-06-3";
+ revision "2014-06-03";
container depth1-cont {
list depth2-cont1 {
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import java.util.Collection;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
+import java.util.function.Function;
import javax.ws.rs.core.UriInfo;
import org.apache.maven.project.MavenProject;
import org.opendaylight.netconf.sal.rest.doc.impl.ApiDocGenerator;
private Map<String, String> additionalConfig;
private File resourceBaseDir;
- /**
- * Generate sources.
- *
- * @param context schema context
- * @param outputDir output directory
- * @param yangModules modules
- * @return {@link Collection} of resource files
- * @throws IOException when file operation fails
- */
@Override
- public Collection<File> generateSources(final SchemaContext context, final File outputDir,
- final Set<Module> yangModules) throws IOException {
+ public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir,
+ final Set<Module> currentModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
+ throws IOException {
List<File> result = new ArrayList<>();
// Create Base Directory
- final File outputBaseDir;
- if (outputDir == null) {
- outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
+ final File outputDir;
+ if (outputBaseDir == null) {
+ outputDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
} else {
- outputBaseDir = outputDir;
+ outputDir = outputBaseDir;
}
- outputBaseDir.mkdirs();
+ outputDir.mkdirs();
// Create Resources directory
- File resourcesDir = new File(outputBaseDir, "resources");
+ File resourcesDir = new File(outputDir, "resources");
resourcesDir.mkdirs();
// Create JS file
- File resourcesJsFile = new File(outputBaseDir, "resources.js");
+ File resourcesJsFile = new File(outputDir, "resources.js");
resourcesJsFile.createNewFile();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resourcesJsFile));
ObjectMapper mapper = new ObjectMapper();
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>2.0.5</version>
+ <version>3.0.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.net.URI;
-import java.text.ParseException;
+import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
-import java.util.GregorianCalendar;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
LOG.info("Modules found [{}]", modules.size());
for (final Module module : modules) {
- final String revisionString = module.getQNameModule().getFormattedRevision();
+ final String revisionString = module.getQNameModule().getRevision().map(Revision::toString).orElse(null);
final Resource resource = new Resource();
LOG.debug("Working on [{},{}]...", module.getName(), revisionString);
final ApiDeclaration doc =
public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo,
final SchemaContext schemaContext, final String context) {
- Date rev = null;
+ final Optional<Revision> rev;
try {
- if (revision != null && !SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(revision)) {
- rev = SimpleDateFormatUtil.getRevisionFormat().parse(revision);
- }
- } catch (final ParseException e) {
+ rev = Revision.ofNullable(revision);
+ } catch (final DateTimeParseException e) {
throw new IllegalArgumentException(e);
}
- if (rev != null) {
- final Calendar cal = new GregorianCalendar();
-
- cal.setTime(rev);
-
- if (cal.get(Calendar.YEAR) < 1970) {
- rev = null;
- }
- }
-
- final Module module = schemaContext.findModuleByName(moduleName, rev);
+ final Module module = schemaContext.findModule(moduleName, rev).orElse(null);
Preconditions.checkArgument(module != null,
"Could not find module by name,revision: " + moduleName + "," + revision);
- return getApiDeclaration(module, rev, uriInfo, context, schemaContext);
+ return getApiDeclaration(module, uriInfo, context, schemaContext);
}
- public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo,
+ public ApiDeclaration getApiDeclaration(final Module module, final UriInfo uriInfo,
final String context, final SchemaContext schemaContext) {
final String basePath = createBasePathFromUriInfo(uriInfo);
final Collection<DataSchemaNode> dataSchemaNodes = module.getChildNodes();
LOG.debug("child nodes size [{}]", dataSchemaNodes.size());
for (final DataSchemaNode node : dataSchemaNodes) {
- if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
+ if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) {
LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName());
List<Parameter> pathParams = new ArrayList<>();
final Api apiForRootPostUri = new Api();
apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore)));
apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX,
- module.getDescription(), module, pathParams, true, ""));
+ module.getDescription().orElse(null), module, pathParams, true, ""));
apis.add(apiForRootPostUri);
}
}
api.setPath(resourcePath.concat(getContent(dataStore)));
Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode>emptySet();
- if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) {
+ if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) {
final DataNodeContainer dataNodeContainer = (DataNodeContainer) node;
childSchemaNodes = dataNodeContainer.getChildNodes();
}
apis.add(api);
for (final DataSchemaNode childNode : childSchemaNodes) {
- if ((childNode instanceof ListSchemaNode) || (childNode instanceof ContainerSchemaNode)) {
+ if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
// keep config and operation attributes separate.
if (childNode.isConfiguration() == addConfigApi) {
final String newParent = parentName + "/" + node.getQName().getLocalName();
operations.add(getBuilder.pathParams(pathParams).build());
if (isConfig) {
- final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName);
+ final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription().orElse(null),
+ parentName);
operations.add(putBuilder.pathParams(pathParams).build());
final Delete deleteBuilder = new Delete(node);
operations.add(deleteBuilder.pathParams(pathParams).build());
if (containsListOrContainer(childSchemaNodes)) {
- operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(),
+ operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription().orElse(null),
(DataNodeContainer) node, pathParams, isConfig, parentName + "/"));
}
}
final String localName = resolvePathArgumentsName(schemaNode, schemaContext);
path.append(localName);
- if ((schemaNode instanceof ListSchemaNode)) {
+ if (schemaNode instanceof ListSchemaNode) {
final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition();
StringBuilder keyBuilder = null;
if (newDraft) {
for (final QName listKey : listKeys) {
final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey);
- pathListParams.add(((LeafSchemaNode) dataChildByName));
+ pathListParams.add((LeafSchemaNode) dataChildByName);
final String pathParamIdentifier;
if (newDraft) {
pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}").toString();
final Parameter pathParam = new Parameter();
pathParam.setName(listKey.getLocalName());
- pathParam.setDescription(dataChildByName.getDescription());
+ pathParam.setDescription(dataChildByName.getDescription().orElse(null));
pathParam.setType("string");
pathParam.setParamType("path");
final Operation operationSpec = new Operation();
operationSpec.setMethod("POST");
- operationSpec.setNotes(rpcDefn.getDescription());
+ operationSpec.setNotes(rpcDefn.getDescription().orElse(null));
operationSpec.setNickname(rpcDefn.getQName().getLocalName());
if (!rpcDefn.getOutput().getChildNodes().isEmpty()) {
operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP);
final SortedSet<Module> sortedModules = new TreeSet<>((module1, module2) -> {
int result = module1.getName().compareTo(module2.getName());
if (result == 0) {
- final Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0);
- final Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0);
- result = module1Revision.compareTo(module2Revision);
+ result = Revision.compare(module1.getRevision(), module2.getRevision());
}
if (result == 0) {
result = module1.getNamespace().compareTo(module2.getNamespace());
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
import com.mifmif.common.regex.Generex;
import java.io.IOException;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import javax.annotation.concurrent.NotThreadSafe;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MandatoryAware;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
dataNodeProperties.put(ITEMS_KEY, items);
- putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription());
+ putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription().orElse(null));
final ObjectNode properties = JsonNodeFactory.instance.objectNode();
properties.put(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
final ObjectNode finalChildSchema = getSchemaTemplate();
LOG.debug("Processing Identity: {}", identityName);
identityObj.put(ID_KEY, identityName);
- putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription());
+ putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription().orElse(null));
final ObjectNode props = JsonNodeFactory.instance.objectNode();
- final IdentitySchemaNode baseId = idNode.getBaseIdentity();
- if (baseId == null) {
+ if (idNode.getBaseIdentities().isEmpty()) {
/*
* This is a base identity. So lets see if it has sub types. If it does, then add them to the model
* definition.
/*
* This is a derived entity. Add it's base type & move on.
*/
- props.put(TYPE_KEY, baseId.getQName().getLocalName());
+ props.put(TYPE_KEY, idNode.getBaseIdentities().iterator().next().getQName().getLocalName());
}
// Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
} else if (node instanceof ChoiceSchemaNode) {
- if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
- processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
- parentName, models, schemaContext, isConfig, properties);
+ if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
+ processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next()
+ .getChildNodes(), parentName, models, schemaContext, isConfig, properties);
}
continue;
} else {
throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
}
- putIfNonNull(property, DESCRIPTION_KEY, node.getDescription());
+ putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
properties.put(topLevelModule.getName() + ":" + name, property);
}
}
props.put(TYPE_KEY, ARRAY_TYPE);
final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode();
- final ConstraintDefinition constraints = listNode.getConstraints();
- int max = constraints.getMaxElements() == null ? 2 : constraints.getMaxElements();
+ final Optional<ElementCountConstraint> optConstraint = listNode.getElementCountConstraint();
+ final int max;
+ if (optConstraint.isPresent()) {
+ final Integer constraintMax = optConstraint.get().getMaxElements();
+ max = constraintMax == null ? 2 : constraintMax;
+ processElementCount(optConstraint.get(), props);
+ } else {
+ max = 2;
+ }
+
if (max >= 2) {
processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
}
props.put(ITEMS_KEY, itemsVal);
-
- processConstraints(constraints, props);
-
return props;
}
property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
} else if (node instanceof ChoiceSchemaNode) {
- if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
- processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
+ if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
+ processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next().getChildNodes(),
moduleName, models, schemaContext, isConfig, properties);
}
continue;
throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
}
- putIfNonNull(property, DESCRIPTION_KEY, node.getDescription());
+ putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
properties.put(name, property);
}
}
- private static void processConstraints(final ConstraintDefinition constraints,
- final ObjectNode props) {
- final boolean isMandatory = constraints.isMandatory();
- props.put(REQUIRED_KEY, isMandatory);
-
- final Integer minElements = constraints.getMinElements();
- final Integer maxElements = constraints.getMaxElements();
+ private static void processElementCount(final ElementCountConstraint constraint, final ObjectNode props) {
+ final Integer minElements = constraint.getMinElements();
if (minElements != null) {
props.put(MIN_ITEMS, minElements);
}
+ final Integer maxElements = constraint.getMaxElements();
if (maxElements != null) {
props.put(MAX_ITEMS, maxElements);
}
}
+ private static void processMandatory(final MandatoryAware node, final ObjectNode props) {
+ props.put(REQUIRED_KEY, node.isMandatory());
+ }
+
private ObjectNode processLeafNode(final LeafSchemaNode leafNode,
final SchemaContext schemaContext) {
final ObjectNode property = JsonNodeFactory.instance.objectNode();
- final String leafDescription = leafNode.getDescription();
+ final String leafDescription = leafNode.getDescription().orElse(null);
putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
- processConstraints(leafNode.getConstraints(), property);
+ processMandatory(leafNode, property);
processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
return property;
private static ObjectNode processAnyXMLNode(final AnyXmlSchemaNode leafNode) {
final ObjectNode property = JsonNodeFactory.instance.objectNode();
- final String leafDescription = leafNode.getDescription();
+ final String leafDescription = leafNode.getDescription().orElse(null);
putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
- processConstraints(leafNode.getConstraints(), property);
+ processMandatory(leafNode, property);
final String localName = leafNode.getQName().getLocalName();
property.put(TYPE_KEY, "example of anyxml " + localName);
} else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
final String name = topLevelModule.getName();
- jsonType =
- name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName();
+ jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentities().iterator().next()
+ .getQName().getLocalName();
} else if (leafTypeDef instanceof StringTypeDefinition) {
jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
} else if (leafTypeDef instanceof BooleanTypeDefinition) {
jsonType = "true";
- } else if (leafTypeDef instanceof DecimalTypeDefinition) {
- jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints()
- .iterator().next().getMin());
-
- } else if (leafTypeDef instanceof IntegerTypeDefinition) {
- jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints()
- .iterator().next().getMin());
-
- } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) {
- jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints()
- .iterator().next().getMin());
+ } else if (leafTypeDef instanceof RangeRestrictedTypeDefinition) {
+ final Number maybeLower = ((RangeRestrictedTypeDefinition<?, ?>) leafTypeDef).getRangeConstraint()
+ .map(RangeConstraint::getAllowedRanges).map(RangeSet::span).map(Range::lowerEndpoint)
+ .orElse(null);
+ jsonType = String.valueOf(maybeLower);
} else {
jsonType = OBJECT_TYPE;
schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
}
- return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
+ return processTypeDef(((TypedDataSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
property, schemaContext);
}
private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
- return schemaContext
- .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision());
+ return schemaContext.findModule(qualifiedName.getNamespace(), qualifiedName.getRevision()).orElse(null);
}
private static String processBinaryType(final ObjectNode property) {
private static String processStringType(final TypeDefinition<?> stringType,
final ObjectNode property, final String nodeName) {
StringTypeDefinition type = (StringTypeDefinition) stringType;
- List<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraints();
- while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
+ Optional<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint();
+ while (!lengthConstraints.isPresent() && type.getBaseType() != null) {
type = type.getBaseType();
- lengthConstraints = type.getLengthConstraints();
+ lengthConstraints = type.getLengthConstraint();
}
- // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
- // and true maximum implied by the constraints and use that.
- for (final LengthConstraint lengthConstraint : lengthConstraints) {
- final Number min = lengthConstraint.getMin();
- final Number max = lengthConstraint.getMax();
- putIfNonNull(property, MIN_LENGTH_KEY, min);
- putIfNonNull(property, MAX_LENGTH_KEY, max);
+ if (lengthConstraints.isPresent()) {
+ final Range<Integer> range = lengthConstraints.get().getAllowedRanges().span();
+ putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint());
+ putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint());
}
+
if (type.getPatternConstraints().iterator().hasNext()) {
final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
- String regex = pattern.getRegularExpression();
+ String regex = pattern.getJavaPatternString();
regex = regex.substring(1, regex.length() - 1);
final Generex generex = new Generex(regex);
return generex.random();
return schemaJSON;
}
- private static void putIfNonNull(ObjectNode property, String key, Number number) {
+ private static void putIfNonNull(final ObjectNode property, final String key, final Number number) {
if (key != null && number != null) {
if (number instanceof Double) {
property.put(key, (Double) number);
}
}
- private static void putIfNonNull(ObjectNode property, String key, String value) {
+ private static void putIfNonNull(final ObjectNode property, final String key, final String value) {
if (key != null && value != null) {
property.put(key, value);
}
CONSUMES_PUT_POST.add("application/xml");
}
+ private OperationBuilder() {
+
+ }
+
public static class Get {
protected Operation spec;
spec.setMethod(METHOD_NAME);
spec.setNickname(METHOD_NAME + "-" + node.getQName().getLocalName());
spec.setType((isConfig ? CONFIG : OPERATIONAL) + node.getQName().getLocalName());
- spec.setNotes(node.getDescription());
+ spec.setNotes(node.getDescription().orElse(null));
}
public Get pathParams(final List<Parameter> params) {
package org.opendaylight.netconf.sal.rest.doc.util;
import java.net.URI;
-import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-public class RestDocgenUtil {
+public final class RestDocgenUtil {
private RestDocgenUtil() {
}
- private static final Map<URI, Map<Date, Module>> NAMESPACE_AND_REVISION_TO_MODULE = new HashMap<>();
+ private static final Map<URI, Map<Optional<Revision>, Module>> NAMESPACE_AND_REVISION_TO_MODULE = new HashMap<>();
/**
* Resolve path argument name for {@code node}.
private static synchronized String resolveFullNameFromNode(final SchemaNode node,
final SchemaContext schemaContext) {
final URI namespace = node.getQName().getNamespace();
- final Date revision = node.getQName().getRevision();
+ final Optional<Revision> revision = node.getQName().getRevision();
- Map<Date, Module> revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.get(namespace);
+ 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.findModuleByNamespaceAndRevision(namespace, revision);
+ module = schemaContext.findModule(namespace, revision).orElse(null);
revisionToModule.put(revision, module);
}
if (module != null) {
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class DocGenTestHelper {
private ObjectMapper mapper;
private SchemaContext schemaContext;
- public Set<Module> loadModules(final String resourceDirectory)
- throws URISyntaxException, FileNotFoundException, ReactorException {
+ public Set<Module> loadModules(final String resourceDirectory) throws URISyntaxException, FileNotFoundException {
final URI resourceDirUri = getClass().getResource(resourceDirectory).toURI();
final File testDir = new File(resourceDirUri);
files.add(new File(testDir, fileName));
}
- this.schemaContext = YangParserTestUtils.parseYangSources(files);
+ this.schemaContext = YangParserTestUtils.parseYangFiles(files);
return this.schemaContext.getModules();
}
when(mockContext.getModules()).thenReturn(this.modules);
final ArgumentCaptor<String> moduleCapture = ArgumentCaptor.forClass(String.class);
- final ArgumentCaptor<Date> dateCapture = ArgumentCaptor.forClass(Date.class);
+ final ArgumentCaptor<Optional> dateCapture = ArgumentCaptor.forClass(Optional.class);
final ArgumentCaptor<URI> namespaceCapture = ArgumentCaptor.forClass(URI.class);
- when(mockContext.findModuleByName(moduleCapture.capture(), dateCapture.capture())).then(
- new Answer<Module>() {
- @Override
- public Module answer(final InvocationOnMock invocation) throws Throwable {
- final String module = moduleCapture.getValue();
- final Date date = dateCapture.getValue();
- for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) {
- if (m.getName().equals(module) && m.getRevision().equals(date)) {
- return m;
- }
- }
- return null;
+ when(mockContext.findModule(moduleCapture.capture(), dateCapture.capture())).then(
+ invocation -> {
+ final String module = moduleCapture.getValue();
+ final Optional<?> date = dateCapture.getValue();
+ for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) {
+ if (m.getName().equals(module) && m.getRevision().equals(date)) {
+ return Optional.of(m);
}
- });
- when(mockContext.findModuleByNamespaceAndRevision(namespaceCapture.capture(), dateCapture.capture())).then(
- new Answer<Module>() {
- @Override
- public Module answer(final InvocationOnMock invocation) throws Throwable {
- final URI namespace = namespaceCapture.getValue();
- final Date date = dateCapture.getValue();
- for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) {
- if (m.getNamespace().equals(namespace) && m.getRevision().equals(date)) {
- return m;
- }
- }
- return null;
+ }
+ return Optional.empty();
+ });
+ when(mockContext.findModule(namespaceCapture.capture(), dateCapture.capture())).then(
+ invocation -> {
+ final URI namespace = namespaceCapture.getValue();
+ final Optional<?> date = dateCapture.getValue();
+ for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) {
+ if (m.getNamespace().equals(namespace) && m.getRevision().equals(date)) {
+ return Optional.of(m);
}
- });
+ }
+ return Optional.empty();
+ });
return mockContext;
}
final ArgumentCaptor<String> subStringCapture = ArgumentCaptor.forClass(String.class);
when(mockBuilder.path(subStringCapture.capture())).thenReturn(mockBuilder);
- when(mockBuilder.build()).then(new Answer<URI>() {
- @Override
- public URI answer(final InvocationOnMock invocation) throws Throwable {
- return URI.create(uri + "/" + subStringCapture.getValue());
- }
- });
+ when(mockBuilder.build()).then(invocation -> URI.create(uri + "/" + subStringCapture.getValue()));
final UriInfo info = mock(UriInfo.class);
private static final String HTTP_URL = "http://localhost/path";
private static final YangInstanceIdentifier INSTANCE_ID = YangInstanceIdentifier.builder()
- .node(QName.create("nodes"))
- .node(QName.create("node"))
- .nodeWithKey(QName.create("node"), QName.create("id"), "123").build();
+ .node(QName.create("", "nodes"))
+ .node(QName.create("", "node"))
+ .nodeWithKey(QName.create("", "node"), QName.create("", "id"), "123").build();
private static final String INSTANCE_URL = "/nodes/node/123/";
private MountPointSwagger swagger;
private DocGenTestHelper helper;
prefix toast;
import toaster2 {prefix tst; revision-date 2009-11-20;}
- revision "2014-7-14" {
+ revision "2014-07-14" {
}
augment "/tst:toaster/tst:toasterSlot" {
}
}
}
-}
\ No newline at end of file
+}