- call-home
Change-Id: I1b5e2db2d6b0a4d3591e56d773cfcd4ffc13ae67
Signed-off-by: Ivan Hrasko <ivan.hrasko@pantheon.tech>
29 files changed:
<groupId>org.opendaylight.netconf</groupId>
<artifactId>netconf-client</artifactId>
</dependency>
<groupId>org.opendaylight.netconf</groupId>
<artifactId>netconf-client</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<scope>test</scope>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
- * FIXME: This should be probably located at AAA library
+ * FIXME: This should be probably located at AAA library.
*/
public class AuthorizedKeysDecoder {
*/
public class AuthorizedKeysDecoder {
private byte[] bytes = new byte[0];
private int pos = 0;
private byte[] bytes = new byte[0];
private int pos = 0;
-
- public PublicKey decodePublicKey(String keyLine) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
+ public PublicKey decodePublicKey(String keyLine)
+ throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
// 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());
// 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());
+ if (bytes.length == 0) {
throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
throw new IllegalArgumentException("No Base64 part to decode in " + keyLine);
pos = 0;
String type = decodeType();
pos = 0;
String type = decodeType();
- if (type.equals(KEY_TYPE_RSA))
+ if (type.equals(KEY_TYPE_RSA)) {
- if (type.equals(KEY_TYPE_DSA))
+ if (type.equals(KEY_TYPE_DSA)) {
- if (type.equals(KEY_TYPE_ECDSA))
- return decodeAsECDSA();
+ if (type.equals(KEY_TYPE_ECDSA)) {
+ return decodeAsEcDSA();
+ }
throw new IllegalArgumentException("Unknown decode key type " + type + " in " + keyLine);
}
throw new IllegalArgumentException("Unknown decode key type " + type + " in " + keyLine);
}
- private PublicKey decodeAsECDSA()
+ private PublicKey decodeAsEcDSA()
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory ecdsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_ECDSA);
ECNamedCurveParameterSpec spec256r1 = ECNamedCurveTable.getParameterSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC);
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory ecdsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_ECDSA);
ECNamedCurveParameterSpec spec256r1 = ECNamedCurveTable.getParameterSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC);
- ECNamedCurveSpec params256r1 = new ECNamedCurveSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC, spec256r1.getCurve(), spec256r1.getG(), spec256r1.getN());
+ ECNamedCurveSpec params256r1 = new ECNamedCurveSpec(
+ ECDSA_SUPPORTED_CURVE_NAME_SPEC, spec256r1.getCurve(), spec256r1.getG(), spec256r1.getN());
// copy last 65 bytes from ssh key.
ECPoint point = ECPointUtil.decodePoint(params256r1.getCurve(), Arrays.copyOfRange(bytes, 39, bytes.length));
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params256r1);
// copy last 65 bytes from ssh key.
ECPoint point = ECPointUtil.decodePoint(params256r1.getCurve(), Arrays.copyOfRange(bytes, 39, bytes.length));
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params256r1);
private PublicKey decodeAsDSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory dsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_DSA);
private PublicKey decodeAsDSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory dsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_DSA);
- BigInteger p = decodeBigInt();
- BigInteger q = decodeBigInt();
- BigInteger g = decodeBigInt();
- BigInteger y = decodeBigInt();
- DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
+ BigInteger prime = decodeBigInt();
+ BigInteger subPrime = decodeBigInt();
+ BigInteger base = decodeBigInt();
+ BigInteger publicKey = decodeBigInt();
+ DSAPublicKeySpec spec = new DSAPublicKeySpec(publicKey, prime, subPrime, base);
return dsaFactory.generatePublic(spec);
}
return dsaFactory.generatePublic(spec);
}
dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length);
dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes());
dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length);
dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes());
- byte[] x = ecPublicKey.getQ().getAffineXCoord().getEncoded();
- byte[] y = ecPublicKey.getQ().getAffineYCoord().getEncoded();
- dout.writeInt(x.length + y.length + 1);
+ byte[] coordX = ecPublicKey.getQ().getAffineXCoord().getEncoded();
+ byte[] coordY = ecPublicKey.getQ().getAffineYCoord().getEncoded();
+ dout.writeInt(coordX.length + coordY.length + 1);
- dout.write(x);
- dout.write(y);
+ dout.write(coordX);
+ dout.write(coordY);
} else {
throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
}
publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
return publicKeyEncoded;
} else {
throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
}
publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
return publicKeyEncoded;
/**
* Returns CallHomeAuthorization object with intent to
* reject incoming connection.
/**
* Returns CallHomeAuthorization object with intent to
* reject incoming connection.
* <p>
* {@link CallHomeAuthorizationProvider} may use returned object
* <p>
* {@link CallHomeAuthorizationProvider} may use returned object
- * as return value for {@link CallHomeAuthorizationProvider#provideAuth(java.net.SocketAddress, java.security.PublicKey)}
+ * as return value for
+ * {@link CallHomeAuthorizationProvider#provideAuth(java.net.SocketAddress, java.security.PublicKey)}
* if the incoming session should be rejected due to policy implemented
* by provider.
*
* if the incoming session should be rejected due to policy implemented
* by provider.
*
/**
* Creates a builder for CallHomeAuthorization with intent
* to accept incoming connection and to provide credentials.
/**
* Creates a builder for CallHomeAuthorization with intent
* to accept incoming connection and to provide credentials.
* <p>
* Note: If session with same sessionName is already opened and
* active, incoming session will be rejected.
* <p>
* Note: If session with same sessionName is already opened and
* active, incoming session will be rejected.
public abstract boolean isServerAllowed();
/**
public abstract boolean isServerAllowed();
/**
- * Applies provided authentification to Mina SSH Client Session
+ * Applies provided authentification to Mina SSH Client Session.
*
* @param session Client Session to which authorization parameters will by applied
*/
*
* @param session Client Session to which authorization parameters will by applied
*/
/**
* Builder for CallHomeAuthorization which accepts incoming connection.
/**
* Builder for CallHomeAuthorization which accepts incoming connection.
* <p>
* Use {@link CallHomeAuthorization#serverAccepted(String, String)} to instantiate
* builder.
* <p>
* Use {@link CallHomeAuthorization#serverAccepted(String, String)} to instantiate
* builder.
private final Set<String> passwords;
private final Set<KeyPair> clientKeyPair;
private final Set<String> passwords;
private final Set<KeyPair> clientKeyPair;
- ServerAllowed(String nodeId, String username, Collection<String> passwords, Collection<KeyPair> clientKeyPairs) {
+ ServerAllowed(String nodeId, String username, Collection<String> passwords,
+ Collection<KeyPair> clientKeyPairs) {
this.username = Preconditions.checkNotNull(username);
this.passwords = ImmutableSet.copyOf(passwords);
this.clientKeyPair = ImmutableSet.copyOf(clientKeyPairs);
this.username = Preconditions.checkNotNull(username);
this.passwords = ImmutableSet.copyOf(passwords);
this.clientKeyPair = ImmutableSet.copyOf(clientKeyPairs);
import javax.annotation.Nonnull;
/**
import javax.annotation.Nonnull;
/**
- * Provider responsible for resolving CallHomeAuthorization
+ * Provider responsible for resolving CallHomeAuthorization.
*/
public interface CallHomeAuthorizationProvider {
*/
public interface CallHomeAuthorizationProvider {
public interface CallHomeChannelActivator {
/**
* Activates Netconf Client Channel with supplied client session listener.
public interface CallHomeChannelActivator {
/**
* Activates Netconf Client Channel with supplied client session listener.
* <p>
* Activation of channel will result in start of NETCONF client
* session negotiation on underlying ssh channel.
* <p>
* Activation of channel will result in start of NETCONF client
* session negotiation on underlying ssh channel.
public interface CallHomeNetconfSubsystemListener {
/**
* Invoked when Netconf Subsystem was successfully opened on incoming SSH Call Home connection.
public interface CallHomeNetconfSubsystemListener {
/**
* Invoked when Netconf Subsystem was successfully opened on incoming SSH Call Home connection.
* <p>
* Implementors of this method should use provided {@link CallHomeChannelActivator} to attach
* {@link NetconfClientSessionListener} to session and to start NETCONF client session negotiation.
* <p>
* Implementors of this method should use provided {@link CallHomeChannelActivator} to attach
* {@link NetconfClientSessionListener} to session and to start NETCONF client session negotiation.
public interface CallHomeProtocolSessionContext {
/**
public interface CallHomeProtocolSessionContext {
/**
- * Returns session identifier provided by CallHomeAuthorizationProvider
+ * Returns session identifier provided by CallHomeAuthorizationProvider.
*
* @return Returns application-provided session identifier
*/
*
* @return Returns application-provided session identifier
*/
- private void channelOpenFailed(Throwable e) {
- LOG.error("Unable to open netconf subsystem, disconnecting.", e);
+ private void channelOpenFailed(Throwable throwable) {
+ LOG.error("Unable to open netconf subsystem, disconnecting.", throwable);
sshSession.close(false);
}
private void netconfChannelOpened(ClientChannel netconfChannel) {
nettyChannel = newMinaSshNettyChannel(netconfChannel);
sshSession.close(false);
}
private void netconfChannelOpened(ClientChannel netconfChannel) {
nettyChannel = newMinaSshNettyChannel(netconfChannel);
- factory.getChannelOpenListener().onNetconfSubsystemOpened(CallHomeSessionContext.this,
- listener -> doActivate(listener));
+ factory.getChannelOpenListener().onNetconfSubsystemOpened(
+ CallHomeSessionContext.this, this::doActivate);
this.context = Preconditions.checkNotNull(context);
this.session = Preconditions.checkNotNull(session);
this.sshChannel = Preconditions.checkNotNull(sshChannel);
this.context = Preconditions.checkNotNull(context);
this.session = Preconditions.checkNotNull(session);
this.sshChannel = Preconditions.checkNotNull(sshChannel);
- this.sshReadHandler = new AsyncSshHandlerReader(new ConnectionClosedDuringRead(), new FireReadMessage(), "netconf",
- sshChannel.getAsyncOut());
+ this.sshReadHandler = new AsyncSshHandlerReader(
+ new ConnectionClosedDuringRead(), new FireReadMessage(), "netconf", sshChannel.getAsyncOut());
this.sshWriteAsyncHandler = new AsyncSshHandlerWriter(sshChannel.getAsyncIn());
pipeline().addFirst(createChannelAdapter());
}
this.sshWriteAsyncHandler = new AsyncSshHandlerWriter(sshChannel.getAsyncIn());
pipeline().addFirst(createChannelAdapter());
}
private final class ConnectionClosedDuringRead implements AutoCloseable {
/**
private final class ConnectionClosedDuringRead implements AutoCloseable {
/**
- * Invoked when SSH session dropped during read using {@link AsyncSshHandlerReader}
+ * Invoked when SSH session dropped during read using {@link AsyncSshHandlerReader}.
*/
@Override
public void close() throws Exception {
*/
@Override
public void close() throws Exception {
protected IoServiceFactory createMinaServiceFactory(SshClient sshClient) {
return new MinaServiceFactory(sshClient);
}
protected IoServiceFactory createMinaServiceFactory(SshClient sshClient) {
return new MinaServiceFactory(sshClient);
}
return new SessionListener() {
@Override
public void sessionEvent(Session session, Event event) {
return new SessionListener() {
@Override
public void sessionEvent(Session session, Event event) {
- ClientSession cSession = (ClientSession) session;
+ ClientSession clientSession = (ClientSession) session;
LOG.debug("SSH session {} event {}", session, event);
switch (event) {
case KeyEstablished:
LOG.debug("SSH session {} event {}", session, event);
switch (event) {
case KeyEstablished:
break;
case Authenticated:
break;
case Authenticated:
+ doPostAuth(clientSession);
- private void doPostAuth(final ClientSession cSession) {
- CallHomeSessionContext.getFrom(cSession).openNetconfChannel();
+ private void doPostAuth(final ClientSession session) {
+ CallHomeSessionContext.getFrom(session).openNetconfChannel();
- private void doAuth(final ClientSession cSession) {
+ private void doAuth(final ClientSession session) {
- final AuthFuture authFuture = CallHomeSessionContext.getFrom(cSession).authorize();
- authFuture.addListener(newAuthSshFutureListener(cSession));
+ final AuthFuture authFuture = CallHomeSessionContext.getFrom(session).authorize();
+ authFuture.addListener(newAuthSshFutureListener(session));
} catch (IOException e) {
} catch (IOException e) {
- LOG.error("Failed to authorize session {}", cSession, e);
+ LOG.error("Failed to authorize session {}", session, e);
- private SshFutureListener<AuthFuture> newAuthSshFutureListener(final ClientSession cSession) {
+ private SshFutureListener<AuthFuture> newAuthSshFutureListener(final ClientSession session) {
return new SshFutureListener<AuthFuture>() {
@Override
public void operationComplete(AuthFuture authFuture) {
return new SshFutureListener<AuthFuture>() {
@Override
public void operationComplete(AuthFuture authFuture) {
}
private void onFailure(Throwable throwable) {
}
private void onFailure(Throwable throwable) {
- ClientSessionImpl impl = (ClientSessionImpl) cSession;
- LOG.error("Authorize failed for session {}", cSession, throwable);
+ ClientSessionImpl impl = (ClientSessionImpl) session;
+ LOG.error("Authorize failed for session {}", session, throwable);
KeyExchange kex = impl.getKex();
PublicKey key = kex.getServerKey();
recorder.reportFailedAuth(key);
KeyExchange kex = impl.getKex();
PublicKey key = kex.getServerKey();
recorder.reportFailedAuth(key);
}
private void onCanceled() {
LOG.warn("Authorize cancelled");
}
private void onCanceled() {
LOG.warn("Authorize cancelled");
LOG.info("Incoming session {} was rejected by Authorization Provider.", sshClientSession);
return false;
}
LOG.info("Incoming session {} was rejected by Authorization Provider.", sshClientSession);
return false;
}
- CallHomeSessionContext session = sessionFactory.createIfNotExists(sshClientSession, authorization, remoteAddress);
+ CallHomeSessionContext session = sessionFactory.createIfNotExists(
+ sshClientSession, authorization, remoteAddress);
// Session was created, session with same name does not exists
if (session != null) {
return true;
}
// Session was not created, session with same name exists
// Session was created, session with same name does not exists
if (session != null) {
return true;
}
// Session was not created, session with same name exists
- LOG.info("Incoming session {} was rejected. Session with same name {} is already active.", sshClientSession, authorization.getSessionName());
+ LOG.info("Incoming session {} was rejected. Session with same name {} is already active.",
+ sshClientSession, authorization.getSessionName());
import org.junit.Before;
import org.junit.Test;
import org.junit.Before;
import org.junit.Test;
public class AuthorizedKeysDecoderTest {
private AuthorizedKeysDecoder instance;
public class AuthorizedKeysDecoderTest {
private AuthorizedKeysDecoder instance;
instance = new AuthorizedKeysDecoder();
}
instance = new AuthorizedKeysDecoder();
}
+ @SuppressWarnings("checkstyle:lineLength")
@Test
public void authorizedKeysDecoderValidRSAKey() throws GeneralSecurityException {
// given
@Test
public void authorizedKeysDecoderValidRSAKey() throws GeneralSecurityException {
// given
assertEquals(serverKey.getAlgorithm(), "RSA");
}
assertEquals(serverKey.getAlgorithm(), "RSA");
}
+ @SuppressWarnings("checkstyle:lineLength")
@Test(expected = Exception.class)
public void authorizedKeysDecoderInvalidRSAKey() throws GeneralSecurityException {
// given
@Test(expected = Exception.class)
public void authorizedKeysDecoderInvalidRSAKey() throws GeneralSecurityException {
// given
instance.decodePublicKey(rsaStr);
}
instance.decodePublicKey(rsaStr);
}
+ @SuppressWarnings("checkstyle:lineLength")
@Test
public void authorizedKeysDecoderValidDSAKey() throws GeneralSecurityException {
// given
@Test
public void authorizedKeysDecoderValidDSAKey() throws GeneralSecurityException {
// given
assertEquals(serverKey.getAlgorithm(), "DSA");
}
assertEquals(serverKey.getAlgorithm(), "DSA");
}
+ @SuppressWarnings("checkstyle:lineLength")
@Test(expected = IllegalArgumentException.class)
public void authorizedKeysDecoderInvalidDSAKey() throws GeneralSecurityException {
// given
@Test(expected = IllegalArgumentException.class)
public void authorizedKeysDecoderInvalidDSAKey() throws GeneralSecurityException {
// given
instance.decodePublicKey(dsaStr);
}
instance.decodePublicKey(dsaStr);
}
+ @SuppressWarnings("checkstyle:lineLength")
- public void authorizedKeysDecoderValidECDSAKey() throws GeneralSecurityException {
+ public void authorizedKeysDecoderValidEcDSAKey() throws GeneralSecurityException {
// given
String ecdsaStr = "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAP4dTrlwZmz8bZ1f901qWuFk7YelrL2WJG0jrCEAPo9UNM1wywpqjbaYUfoq+cevhLZaukDQ4N2Evux+YQ2zz0=";
// when
// given
String ecdsaStr = "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAP4dTrlwZmz8bZ1f901qWuFk7YelrL2WJG0jrCEAPo9UNM1wywpqjbaYUfoq+cevhLZaukDQ4N2Evux+YQ2zz0=";
// when
assertEquals(serverKey.getAlgorithm(), "EC");
}
assertEquals(serverKey.getAlgorithm(), "EC");
}
+ @SuppressWarnings("checkstyle:lineLength")
@Test(expected = IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
- public void authorizedKeysDecoderInvalidECDSAKey() throws GeneralSecurityException {
+ public void authorizedKeysDecoderInvalidEcDSAKey() throws GeneralSecurityException {
// given
String ecdsaStr = "AAAAE2VjZHNhLXNoItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAP4dTrlwZmz8bZ1f901qWuFk7YelrL2WJG0jrCEAPo9UNM1wywpqjbaYUfoq+cevhLZaukDQ4N2Evux+YQ2zz0=";
// when
// given
String ecdsaStr = "AAAAE2VjZHNhLXNoItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAP4dTrlwZmz8bZ1f901qWuFk7YelrL2WJG0jrCEAPo9UNM1wywpqjbaYUfoq+cevhLZaukDQ4N2Evux+YQ2zz0=";
// when
import org.apache.sshd.client.session.ClientSessionImpl;
import org.junit.Test;
import org.apache.sshd.client.session.ClientSessionImpl;
import org.junit.Test;
public class CallHomeAuthorizationTest {
@Test
public void anAuthorizationOfRejectedIsNotAllowed() {
public class CallHomeAuthorizationTest {
@Test
public void anAuthorizationOfRejectedIsNotAllowed() {
// given
instance = realFactory.createIfNotExists(mockSession, mockAuth, address);
// given
instance = realFactory.createIfNotExists(mockSession, mockAuth, address);
- SshFutureListener<OpenFuture> listener = instance.newSshFutureListener(mockChannel);
OpenFuture mockFuture = mock(OpenFuture.class);
Mockito.doReturn(false).when(mockFuture).isOpened();
Mockito.doReturn(new RuntimeException("test")).when(mockFuture).getException();
OpenFuture mockFuture = mock(OpenFuture.class);
Mockito.doReturn(false).when(mockFuture).isOpened();
Mockito.doReturn(new RuntimeException("test")).when(mockFuture).getException();
doReturn(null).when(mockSession).close(anyBoolean());
// when
doReturn(null).when(mockSession).close(anyBoolean());
// when
+ SshFutureListener<OpenFuture> listener = instance.newSshFutureListener(mockChannel);
listener.operationComplete(mockFuture);
// then
// You'll see an error message logged to the console - it is expected.
listener.operationComplete(mockFuture);
// then
// You'll see an error message logged to the console - it is expected.
import org.junit.Test;
import org.mockito.Mockito;
import org.junit.Test;
import org.mockito.Mockito;
public class MinaSshNettyChannelTest {
private CallHomeSessionContext mockContext;
private ClientSession mockSession;
public class MinaSshNettyChannelTest {
private CallHomeSessionContext mockContext;
private ClientSession mockSession;
IoReadFuture mockFuture = mock(IoReadFuture.class);
IoInputStream mockIn = mock(IoInputStream.class);
Mockito.doReturn(mockFuture).when(mockIn).read(any(Buffer.class));
IoReadFuture mockFuture = mock(IoReadFuture.class);
IoInputStream mockIn = mock(IoInputStream.class);
Mockito.doReturn(mockFuture).when(mockIn).read(any(Buffer.class));
- IoOutputStream mockOut = mock(IoOutputStream.class);
mockContext = mock(CallHomeSessionContext.class);
mockSession = mock(ClientSession.class);
mockChannel = mock(ClientChannel.class);
Mockito.doReturn(mockIn).when(mockChannel).getAsyncOut();
mockContext = mock(CallHomeSessionContext.class);
mockSession = mock(ClientSession.class);
mockChannel = mock(ClientChannel.class);
Mockito.doReturn(mockIn).when(mockChannel).getAsyncOut();
+
+ IoOutputStream mockOut = mock(IoOutputStream.class);
Mockito.doReturn(mockOut).when(mockChannel).getAsyncIn();
IoWriteFuture mockWrFuture = mock(IoWriteFuture.class);
Mockito.doReturn(mockOut).when(mockChannel).getAsyncIn();
IoWriteFuture mockWrFuture = mock(IoWriteFuture.class);
Mockito.doReturn(mockHandler).when(ctx).handler();
ChannelPromise promise = mock(ChannelPromise.class);
Mockito.doReturn(mockHandler).when(ctx).handler();
ChannelPromise promise = mock(ChannelPromise.class);
- ByteBufAllocator mockAlloc = mock(ByteBufAllocator.class);
- ByteBuf bytes = new EmptyByteBuf(mockAlloc);
-
// we would really like to just verify that the async handler write() was
// called but it is a final class, so no mocking. instead we set up the
// mock channel to have no async input, which will cause a failure later
// we would really like to just verify that the async handler write() was
// called but it is a final class, so no mocking. instead we set up the
// mock channel to have no async input, which will cause a failure later
// when
ChannelOutboundHandlerAdapter outadapter = (ChannelOutboundHandlerAdapter) instance.pipeline().first();
// when
ChannelOutboundHandlerAdapter outadapter = (ChannelOutboundHandlerAdapter) instance.pipeline().first();
+ ByteBufAllocator mockAlloc = mock(ByteBufAllocator.class);
+ ByteBuf bytes = new EmptyByteBuf(mockAlloc);
outadapter.write(ctx, bytes, promise);
// then
outadapter.write(ctx, bytes, promise);
// then
props.put("nio-workers", "1");
Mockito.doReturn(props).when(mockSshClient).getProperties();
Mockito.doReturn("test").when(mockSession).toString();
props.put("nio-workers", "1");
Mockito.doReturn(props).when(mockSshClient).getProperties();
Mockito.doReturn("test").when(mockSession).toString();
- instance = new NetconfCallHomeServer(mockSshClient, mockCallHomeAuthProv, mockFactory, mockAddress, mockStatusRecorder);
+ instance = new NetconfCallHomeServer(
+ mockSshClient, mockCallHomeAuthProv, mockFactory, mockAddress, mockStatusRecorder);
Mockito.doReturn(mockAcceptor).when(mockMinaFactory).createAcceptor(any(IoHandler.class));
Mockito.doReturn(mockAcceptor).when(mockMinaFactory).createAcceptor(any(IoHandler.class));
Mockito.doNothing().when(mockAcceptor).bind(mockAddress);
Mockito.doReturn(mockAcceptor).when(mockMinaFactory).createAcceptor(any(IoHandler.class));
Mockito.doReturn(mockAcceptor).when(mockMinaFactory).createAcceptor(any(IoHandler.class));
Mockito.doNothing().when(mockAcceptor).bind(mockAddress);
- instance = new TestableCallHomeServer(mockSshClient, mockCallHomeAuthProv, mockFactory, mockAddress, mockMinaFactory, mockStatusRecorder);
+ instance = new TestableCallHomeServer(
+ mockSshClient, mockCallHomeAuthProv, mockFactory, mockAddress, mockMinaFactory, mockStatusRecorder);
// when
instance.bind();
// then
// when
instance.bind();
// then
<artifactId>mockito-core</artifactId>
</dependency>
</dependencies>
<artifactId>mockito-core</artifactId>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
statusReporter.asForceListedDevice(syntheticId, serverKey);
} else {
Device opDevice = deviceOp.get(serverKey);
statusReporter.asForceListedDevice(syntheticId, serverKey);
} else {
Device opDevice = deviceOp.get(serverKey);
+ if (opDevice == null) {
statusReporter.asUnlistedDevice(syntheticId, serverKey);
statusReporter.asUnlistedDevice(syntheticId, serverKey);
LOG.info("Repeating rejection of unlisted device with id of {}", opDevice.getUniqueId());
LOG.info("Repeating rejection of unlisted device with id of {}", opDevice.getUniqueId());
return CallHomeAuthorization.rejected();
}
}
return CallHomeAuthorization.rejected();
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CallHomeMountDispatcher implements NetconfClientDispatcher, CallHomeNetconfSubsystemListener {
public class CallHomeMountDispatcher implements NetconfClientDispatcher, CallHomeNetconfSubsystemListener {
- private final static Logger LOG = LoggerFactory.getLogger(CallHomeMountDispatcher.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CallHomeMountDispatcher.class);
private final String topologyId;
private final EventExecutor eventExecutor;
private final String topologyId;
private final EventExecutor eventExecutor;
@Override
public void onNetconfSubsystemOpened(final CallHomeProtocolSessionContext session,
final CallHomeChannelActivator activator) {
@Override
public void onNetconfSubsystemOpened(final CallHomeProtocolSessionContext session,
final CallHomeChannelActivator activator) {
- final CallHomeMountSessionContext deviceContext = getSessionManager().createSession(session, activator, onCloseHandler);
+ final CallHomeMountSessionContext deviceContext = getSessionManager()
+ .createSession(session, activator, onCloseHandler);
final NodeId nodeId = deviceContext.getId();
final Node configNode = deviceContext.getConfigNode();
LOG.info("Provisioning fake config {}", configNode);
final NodeId nodeId = deviceContext.getId();
final Node configNode = deviceContext.getConfigNode();
LOG.info("Provisioning fake config {}", configNode);
- public void onSessionDown(NetconfClientSession session, Exception e) {
+ public void onSessionDown(NetconfClientSession session, Exception exc) {
try {
removeSelf();
} finally {
try {
removeSelf();
} finally {
- delegate.onSessionDown(session, e);
+ delegate.onSessionDown(session, exc);
public class CallHomeMountSessionManager implements CallHomeMountSessionContext.CloseCallback {
public class CallHomeMountSessionManager implements CallHomeMountSessionContext.CloseCallback {
- private final ConcurrentMap<SocketAddress, CallHomeMountSessionContext> contextByAddress = new ConcurrentHashMap<>();
- private final Multimap<PublicKey, CallHomeMountSessionContext> contextByPublicKey = MultimapBuilder.hashKeys().hashSetValues().build();
+ private final ConcurrentMap<SocketAddress, CallHomeMountSessionContext> contextByAddress =
+ new ConcurrentHashMap<>();
+ private final Multimap<PublicKey, CallHomeMountSessionContext> contextByPublicKey = MultimapBuilder.hashKeys()
+ .hashSetValues().build();
@Nullable
public CallHomeMountSessionContext getByAddress(InetSocketAddress remoteAddr) {
@Nullable
public CallHomeMountSessionContext getByAddress(InetSocketAddress remoteAddr) {
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
public class CallHomeTopology extends BaseCallHomeTopology {
public CallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
public class CallHomeTopology extends BaseCallHomeTopology {
public CallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class CallhomeStatusReporter implements DataChangeListener, StatusRecorder, AutoCloseable {
private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID =
InstanceIdentifier.create(NetworkTopology.class).child(Topology.class,
class CallhomeStatusReporter implements DataChangeListener, StatusRecorder, AutoCloseable {
private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID =
InstanceIdentifier.create(NetworkTopology.class).child(Topology.class,
CallhomeStatusReporter(DataBroker broker) {
this.dataBroker = broker;
CallhomeStatusReporter(DataBroker broker) {
this.dataBroker = broker;
- this.reg = dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, NETCONF_TOPO_IID.child(Node.class),
- this, AsyncDataBroker.DataChangeScope.SUBTREE);
+ this.reg = dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
+ NETCONF_TOPO_IID.child(Node.class), this, AsyncDataBroker.DataChangeScope.SUBTREE);
}
@Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
for (InstanceIdentifier<?> removedPath : change.getRemovedPaths()) {
}
@Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
for (InstanceIdentifier<?> removedPath : change.getRemovedPaths()) {
- if (removedPath.getTargetType() != NetconfNode.class)
+ if (removedPath.getTargetType() != NetconfNode.class) {
final NodeId nodeId = getNodeId(removedPath);
if (nodeId != null) {
final NodeId nodeId = getNodeId(removedPath);
if (nodeId != null) {
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withConnectedStatus(opDev);
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withConnectedStatus(opDev);
- if (modifiedDevice == null)
+ if (modifiedDevice == null) {
LOG.info("Setting successful status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
LOG.info("Setting successful status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withDisconnectedStatus(opDev);
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withDisconnectedStatus(opDev);
- if (modifiedDevice == null)
+ if (modifiedDevice == null) {
LOG.info("Setting disconnected status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
LOG.info("Setting disconnected status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withFailedStatus(opDev);
LOG.warn("No corresponding callhome device found - exiting.");
} else {
Device modifiedDevice = withFailedStatus(opDev);
- if (modifiedDevice == null)
+ if (modifiedDevice == null) {
LOG.info("Setting failed status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
LOG.info("Setting failed status for callhome device id:{}.", nodeId);
writeDevice(nodeId, modifiedDevice);
}
try {
sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
} catch (IOException e) {
try {
sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
} catch (IOException e) {
- e.printStackTrace();
- LOG.warn("Unable to encode public key to ssh format.");
+ LOG.warn("Unable to encode public key to ssh format.", e);
}
Device1 d1 = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILEDNOTALLOWED).build();
DeviceBuilder builder = new DeviceBuilder()
}
Device1 d1 = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILEDNOTALLOWED).build();
DeviceBuilder builder = new DeviceBuilder()
private void setDeviceStatus(Device device) {
WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
private void setDeviceStatus(Device device) {
WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
- InstanceIdentifier<Device> Device_IID =
+ InstanceIdentifier<Device> deviceIId =
InstanceIdentifier.create(NetconfCallhomeServer.class)
.child(AllowedDevices.class)
.child(Device.class, device.getKey());
InstanceIdentifier.create(NetconfCallhomeServer.class)
.child(AllowedDevices.class)
.child(Device.class, device.getKey());
- tx.merge(LogicalDatastoreType.OPERATIONAL, Device_IID, device);
+ tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIId, device);
private AllowedDevices getDevices() {
ReadOnlyTransaction rxTransaction = dataBroker.newReadOnlyTransaction();
CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture =
private AllowedDevices getDevices() {
ReadOnlyTransaction rxTransaction = dataBroker.newReadOnlyTransaction();
CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture =
PublicKey pubKey = decoder.decodePublicKey(keyString);
if (sshKey.getAlgorithm().equals(pubKey.getAlgorithm()) && sshKey.equals(pubKey)) {
Device failedDevice = withFailedAuthStatus(device);
PublicKey pubKey = decoder.decodePublicKey(keyString);
if (sshKey.getAlgorithm().equals(pubKey.getAlgorithm()) && sshKey.equals(pubKey)) {
Device failedDevice = withFailedAuthStatus(device);
- if (failedDevice == null)
+ if (failedDevice == null) {
LOG.info("Setting auth failed status for callhome device id:{}.", failedDevice.getUniqueId());
setDeviceStatus(failedDevice);
return;
LOG.info("Setting auth failed status for callhome device id:{}.", failedDevice.getUniqueId());
setDeviceStatus(failedDevice);
return;
}
public static class ReadException extends ConfigurationException {
}
public static class ReadException extends ConfigurationException {
- ReadException(String msg, Exception e) {
- super(msg, e);
+ ReadException(String msg, Exception exc) {
+ super(msg, exc);
String get(String key) {
String result = (String) properties.get(key);
String get(String key) {
String result = (String) properties.get(key);
throw new MissingException(key);
throw new MissingException(key);
return result;
}
public int getAsPort(String key) {
return result;
}
public int getAsPort(String key) {
+ String keyValue = get(key);
- int newPort = Integer.parseInt(s);
- if (newPort < 0 || newPort > 65535)
- throw new IllegalValueException(key, s);
+ int newPort = Integer.parseInt(keyValue);
+ if (newPort < 0 || newPort > 65535) {
+ throw new IllegalValueException(key, keyValue);
+ }
return newPort;
} catch (NumberFormatException e) {
return newPort;
} catch (NumberFormatException e) {
- throw new IllegalValueException(key, s);
+ throw new IllegalValueException(key, keyValue);
@Override
public boolean equals(Object obj) {
@Override
public boolean equals(Object obj) {
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
ContextKey other = (ContextKey) obj;
return Objects.equal(address, other.address) && Objects.equal(port, other.port);
}
ContextKey other = (ContextKey) obj;
return Objects.equal(address, other.address) && Objects.equal(port, other.port);
}
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataChangeListener {
private static final String APPNAME = "CallHomeServer";
public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataChangeListener {
private static final String APPNAME = "CallHomeServer";
- static final InstanceIdentifier<AllowedDevices> ALL_DEVICES = InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class);
+ static final InstanceIdentifier<AllowedDevices> ALL_DEVICES = InstanceIdentifier.create(NetconfCallhomeServer.class)
+ .child(AllowedDevices.class);
private static final Logger LOG = LoggerFactory.getLogger(IetfZeroTouchCallHomeServerProvider.class);
private static final Logger LOG = LoggerFactory.getLogger(IetfZeroTouchCallHomeServerProvider.class);
try {
LOG.info("Initializing provider for {}", APPNAME);
initializeServer();
try {
LOG.info("Initializing provider for {}", APPNAME);
initializeServer();
- dataBroker.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, ALL_DEVICES, this, AsyncDataBroker.DataChangeScope.SUBTREE);
+ dataBroker.registerDataChangeListener(
+ LogicalDatastoreType.CONFIGURATION, ALL_DEVICES, this, AsyncDataBroker.DataChangeScope.SUBTREE);
LOG.info("Initialization complete for {}", APPNAME);
} catch (IOException | Configuration.ConfigurationException e) {
LOG.error("Unable to successfully initialize", e);
LOG.info("Initialization complete for {}", APPNAME);
} catch (IOException | Configuration.ConfigurationException e) {
LOG.error("Unable to successfully initialize", e);
configuration.set(CALL_HOME_PORT_KEY, portStr);
port = configuration.getAsPort(CALL_HOME_PORT_KEY);
LOG.info("Setting port for call home server to {}", portStr);
configuration.set(CALL_HOME_PORT_KEY, portStr);
port = configuration.getAsPort(CALL_HOME_PORT_KEY);
LOG.info("Setting port for call home server to {}", portStr);
- } catch(Configuration.ConfigurationException e) {
+ } catch (Configuration.ConfigurationException e) {
LOG.error("Problem trying to set port for call home server {}", portStr, e);
}
}
LOG.error("Problem trying to set port for call home server {}", portStr, e);
}
}
CallHomeAuthorizationProvider provider = this.getCallHomeAuthorization();
NetconfCallHomeServerBuilder builder = new NetconfCallHomeServerBuilder(
provider, mountDispacher, statusReporter);
CallHomeAuthorizationProvider provider = this.getCallHomeAuthorization();
NetconfCallHomeServerBuilder builder = new NetconfCallHomeServerBuilder(
provider, mountDispacher, statusReporter);
builder.setBindAddress(new InetSocketAddress(port));
builder.setBindAddress(new InetSocketAddress(port));
server = builder.build();
server.bind();
mountDispacher.createTopology();
server = builder.build();
server.bind();
mountDispacher.createTopology();
@VisibleForTesting
void assertValid(Object obj, String description) {
@VisibleForTesting
void assertValid(Object obj, String description) {
- if (obj == null)
- throw new RuntimeException(String.format("Failed to find %s in IetfZeroTouchCallHomeProvider.initialize()", description));
+ if (obj == null) {
+ throw new RuntimeException(
+ String.format("Failed to find %s in IetfZeroTouchCallHomeProvider.initialize()", description));
+ }
CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture =
roConfigTx.read(LogicalDatastoreType.CONFIGURATION, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES);
CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture =
roConfigTx.read(LogicalDatastoreType.CONFIGURATION, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES);
- if (hasDeletedDevices(change))
+ if (hasDeletedDevices(change)) {
handleDeletedDevices(change);
handleDeletedDevices(change);
try {
for (Device confDevice : getReadDevices(devicesFuture)) {
try {
for (Device confDevice : getReadDevices(devicesFuture)) {
opTx.delete(LogicalDatastoreType.OPERATIONAL, removedIID);
}
opTx.delete(LogicalDatastoreType.OPERATIONAL, removedIID);
}
}
private List<Device> getReadDevices(CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture)
}
private List<Device> getReadDevices(CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture)
.child(Device.class, new DeviceKey(cfgDevice.getUniqueId()));
ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
.child(Device.class, new DeviceKey(cfgDevice.getUniqueId()));
ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
- CheckedFuture<Optional<Device>, ReadFailedException> deviceFuture = tx.read(LogicalDatastoreType.OPERATIONAL, deviceIID);
+ CheckedFuture<Optional<Device>, ReadFailedException> deviceFuture = tx.read(
+ LogicalDatastoreType.OPERATIONAL, deviceIID);
Optional<Device> opDevGet = deviceFuture.checkedGet();
Device1 devStatus = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build();
Optional<Device> opDevGet = deviceFuture.checkedGet();
Device1 devStatus = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build();
<argument ref="domMountPointService"/>
</bean>
<argument ref="domMountPointService"/>
</bean>
</blueprint>
\ No newline at end of file
</blueprint>
\ No newline at end of file
public CallHomeMountSessionManager getSessionManager() {
return mockSessMgr;
}
public CallHomeMountSessionManager getSessionManager() {
return mockSessMgr;
}
@Override
void createTopology() {
this.topology = mockTopology;
@Override
void createTopology() {
this.topology = mockTopology;
import org.opendaylight.netconf.client.NetconfClientSession;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
import org.opendaylight.netconf.client.NetconfClientSession;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
public class CallHomeMountSessionContextTest {
private Inet4Address someAddressIpv4;
private InetSocketAddress someSocketAddress;
public class CallHomeMountSessionContextTest {
private Inet4Address someAddressIpv4;
private InetSocketAddress someSocketAddress;
public void activationOfListenerSupportsSessionUp() {
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
public void activationOfListenerSupportsSessionUp() {
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
- .thenAnswer(invocationOnMock -> {
- NetconfClientSession mockSession = mock(NetconfClientSession.class);
+ .thenAnswer(invocationOnMock -> {
+ NetconfClientSession mockSession = mock(NetconfClientSession.class);
- Object arg = invocationOnMock.getArguments()[0];
- ((NetconfClientSessionListener) arg).onSessionUp(mockSession);
- return null;
- });
+ Object arg = invocationOnMock.getArguments()[0];
+ ((NetconfClientSessionListener) arg).onSessionUp(mockSession);
+ return null;
+ });
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
- NetconfClientSession mockSession = mock(NetconfClientSession.class);
- NetconfTerminationReason mockReason = mock(NetconfTerminationReason.class);
+ NetconfClientSession mockSession = mock(NetconfClientSession.class);
+ NetconfTerminationReason mockReason = mock(NetconfTerminationReason.class);
- Object arg = invocationOnMock.getArguments()[0];
- ((NetconfClientSessionListener) arg).onSessionTerminated(mockSession, mockReason);
- return null;
- });
+ Object arg = invocationOnMock.getArguments()[0];
+ ((NetconfClientSessionListener) arg).onSessionTerminated(mockSession, mockReason);
+ return null;
+ });
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
- NetconfClientSession mockSession = mock(NetconfClientSession.class);
- Exception mockException = mock(Exception.class);
+ NetconfClientSession mockSession = mock(NetconfClientSession.class);
+ Exception mockException = mock(Exception.class);
- Object arg = invocationOnMock.getArguments()[0];
- ((NetconfClientSessionListener) arg).onSessionDown(mockSession, mockException);
- return null;
- });
+ Object arg = invocationOnMock.getArguments()[0];
+ ((NetconfClientSessionListener) arg).onSessionDown(mockSession, mockException);
+ return null;
+ });
// given
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
// given
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
// given
when(mockActivator.activate(any(NetconfClientSessionListener.class)))
.thenAnswer(invocationOnMock -> {
- NetconfClientSession mockSession = mock(NetconfClientSession.class);
- NetconfMessage mockMsg = mock(NetconfMessage.class);
+ NetconfClientSession mockSession = mock(NetconfClientSession.class);
+ NetconfMessage mockMsg = mock(NetconfMessage.class);
- Object arg = invocationOnMock.getArguments()[0];
- ((NetconfClientSessionListener) arg).onMessage(mockSession, mockMsg);
- return null;
- });
+ Object arg = invocationOnMock.getArguments()[0];
+ ((NetconfClientSessionListener) arg).onMessage(mockSession, mockMsg);
+ return null;
+ });
// given
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
// given
NetconfClientSessionListener mockListener = mock(NetconfClientSessionListener.class);
// when
package org.opendaylight.netconf.callhome.mount;
package org.opendaylight.netconf.callhome.mount;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
public class ContextKeyTest {
private IpAddress address1;
private IpAddress address2;
public class ContextKeyTest {
private IpAddress address1;
private IpAddress address2;