From: Maros Marsalek Date: Wed, 3 Sep 2014 12:22:43 +0000 (+0200) Subject: Refactor integration tests for netconf in netconf-it X-Git-Tag: release/helium~152^2 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=8a883b7174c700d7f11f77c7e21ad0b7e1787cd5 Refactor integration tests for netconf in netconf-it Change-Id: I03c8a9220dc1fa115f6489219df6a45297bbd28e Signed-off-by: Maros Marsalek --- diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java index d4073e5c17..bd931c33d0 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/AbstractNetconfConfigTest.java @@ -7,47 +7,209 @@ */ package org.opendaylight.controller.netconf.it; -import java.net.InetSocketAddress; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anySetOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.util.HashedWheelTimer; +import io.netty.util.concurrent.GlobalEventExecutor; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Before; import org.opendaylight.controller.config.manager.impl.AbstractConfigTest; +import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; +import org.opendaylight.controller.config.spi.ModuleFactory; +import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory; +import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory; +import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory; +import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory; +import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory; +import org.opendaylight.controller.netconf.api.NetconfMessage; +import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder; +import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl; +import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; +import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService; +import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl; +import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot; import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher; import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory; import org.opendaylight.controller.netconf.impl.SessionIdProvider; +import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl; import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl; +import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl; import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory; +import org.opendaylight.controller.netconf.util.test.XmlFileLoader; import org.opendaylight.protocol.framework.NeverReconnectStrategy; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; +import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl; +import org.w3c.dom.Element; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.util.HashedWheelTimer; -import io.netty.util.concurrent.GlobalEventExecutor; +public abstract class AbstractNetconfConfigTest extends AbstractConfigTest { -public class AbstractNetconfConfigTest extends AbstractConfigTest { + public static final String LOOPBACK_ADDRESS = "127.0.0.1"; + public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000; + + static ModuleFactory[] FACTORIES = { new TestImplModuleFactory(), + new DepTestImplModuleFactory(), new NetconfTestImplModuleFactory(), + new IdentityTestModuleFactory(), new MultipleDependenciesModuleFactory() }; private EventLoopGroup nettyThreadgroup; private HashedWheelTimer hashedWheelTimer; + private NetconfClientDispatcherImpl clientDispatcher; + private Channel serverTcpChannel; + + private NetconfMessage getConfig; + private NetconfMessage get; + + /** + * @Before in subclasses is called after this method. + */ @Before - public void setUpAbstractNetconfConfigTest() { + public void setUpAbstractNetconfConfigTest() throws Exception { + super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORIES)); + nettyThreadgroup = new NioEventLoopGroup(); hashedWheelTimer = new HashedWheelTimer(); + + loadMessages(); + + setUpTestInitial(); + + final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl(); + factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore())); + + for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories()) { + factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory); + } + + serverTcpChannel = startNetconfTcpServer(factoriesListener); + clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer()); + } + + /** + * Called before setUp method is executed, so test classes can set up resources before setUpAbstractNetconfConfigTest method is called. + */ + protected void setUpTestInitial() throws Exception {} + + private void loadMessages() throws Exception { + this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml"); + this.get = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml"); + } + + public NetconfMessage getGetConfig() { + return getConfig; + } + + public NetconfMessage getGet() { + return get; + } + + private Channel startNetconfTcpServer(final NetconfOperationServiceFactoryListenerImpl factoriesListener) throws Exception { + final NetconfServerDispatcher dispatch = createDispatcher(factoriesListener, getNetconfMonitoringService(), getNotificationProducer()); + + final ChannelFuture s; + if(getTcpServerAddress() instanceof LocalAddress) { + s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress())); + } else { + s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress())); + } + s.await(); + return s.channel(); + } + + protected DefaultCommitNotificationProducer getNotificationProducer() { + final DefaultCommitNotificationProducer notificationProducer = mock(DefaultCommitNotificationProducer.class); + doNothing().when(notificationProducer).close(); + doNothing().when(notificationProducer).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class)); + return notificationProducer; + } + + protected Iterable getAdditionalServiceFactories() { + return Collections.emptySet(); + } + + protected SessionMonitoringService getNetconfMonitoringService() throws Exception { + final NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class); + final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); + doReturn(Collections.emptySet()).when(snap).getServices(); + doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString()); + return new NetconfMonitoringServiceImpl(netconfOperationProvider); + } + + protected abstract SocketAddress getTcpServerAddress(); + + public NetconfClientDispatcherImpl getClientDispatcher() { + return clientDispatcher; + } + + private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException { + final Collection yangDependencies = getBasicYangs(); + return new HardcodedYangStoreService(yangDependencies); + } + + static Collection getBasicYangs() throws IOException { + + final List paths = Arrays.asList( + "/META-INF/yang/config.yang", + "/META-INF/yang/rpc-context.yang", + "/META-INF/yang/config-test.yang", + "/META-INF/yang/config-test-impl.yang", + "/META-INF/yang/test-types.yang", + "/META-INF/yang/ietf-inet-types.yang"); + + final Collection yangDependencies = new ArrayList<>(); + final List failedToFind = new ArrayList<>(); + for (final String path : paths) { + final InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path); + if (resourceAsStream == null) { + failedToFind.add(path); + } else { + yangDependencies.add(resourceAsStream); + } + } + assertEquals("Some yang files were not found", Collections.emptyList(), failedToFind); + return yangDependencies; } protected NetconfServerDispatcher createDispatcher( - NetconfOperationServiceFactoryListenerImpl factoriesListener, SessionMonitoringService sessionMonitoringService, - DefaultCommitNotificationProducer commitNotifier) { - SessionIdProvider idProvider = new SessionIdProvider(); + final NetconfOperationServiceFactoryListenerImpl factoriesListener, final SessionMonitoringService sessionMonitoringService, + final DefaultCommitNotificationProducer commitNotifier) { + final SessionIdProvider idProvider = new SessionIdProvider(); - NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory( - hashedWheelTimer, factoriesListener, idProvider, 5000, commitNotifier, sessionMonitoringService); + final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory( + hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, commitNotifier, sessionMonitoringService); - NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer( + final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer( serverNegotiatorFactory); return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup); } @@ -60,19 +222,58 @@ public class AbstractNetconfConfigTest extends AbstractConfigTest { return nettyThreadgroup; } + /** + * @After in subclasses is be called before this. + */ @After - public void cleanUpTimer() { + public void cleanUpNetconf() throws Exception { + serverTcpChannel.close().await(); hashedWheelTimer.stop(); - nettyThreadgroup.shutdownGracefully(); + nettyThreadgroup.shutdownGracefully().await(); } public NetconfClientConfiguration getClientConfiguration(final InetSocketAddress tcpAddress, final int timeout) { final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create(); b.withAddress(tcpAddress); b.withSessionListener(new SimpleNetconfClientSessionListener()); - b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, - timeout)); + b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, timeout)); b.withConnectionTimeoutMillis(timeout); return b.build(); } + + public static final class HardcodedYangStoreService implements YangStoreService { + + private final List byteArrayInputStreams; + + public HardcodedYangStoreService(final Collection inputStreams) throws YangStoreException, IOException { + byteArrayInputStreams = new ArrayList<>(); + for (final InputStream inputStream : inputStreams) { + assertNotNull(inputStream); + final byte[] content = IOUtils.toByteArray(inputStream); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); + byteArrayInputStreams.add(byteArrayInputStream); + } + } + + @Override + public YangStoreSnapshot getYangStoreSnapshot() throws YangStoreException { + for (final InputStream inputStream : byteArrayInputStreams) { + try { + inputStream.reset(); + } catch (final IOException e) { + throw new RuntimeException(e); + } + } + + final YangParserImpl yangParser = new YangParserImpl(); + final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(byteArrayInputStreams).values())); + final YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() { + @Override + public SchemaContext getSchemaContext() { + return schemaContext ; + } + }); + return yangStoreService.getYangStoreSnapshot(); + } + } } diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/HardcodedYangStoreService.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/HardcodedYangStoreService.java deleted file mode 100644 index 3fa1b0195a..0000000000 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/HardcodedYangStoreService.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.it; - -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; -import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl; - -public class HardcodedYangStoreService implements YangStoreService { - - private final List byteArrayInputStreams; - - public HardcodedYangStoreService( - Collection inputStreams) - throws YangStoreException, IOException { - byteArrayInputStreams = new ArrayList<>(); - for (InputStream inputStream : inputStreams) { - assertNotNull(inputStream); - byte[] content = IOUtils.toByteArray(inputStream); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - content); - byteArrayInputStreams.add(byteArrayInputStream); - } - } - - @Override - public YangStoreSnapshot getYangStoreSnapshot() throws YangStoreException { - for (InputStream inputStream : byteArrayInputStreams) { - try { - inputStream.reset(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - YangParserImpl yangParser = new YangParserImpl(); - final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(byteArrayInputStreams).values())); - YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() { - @Override - public SchemaContext getSchemaContext() { - return schemaContext ; - } - }); - return yangStoreService.getYangStoreSnapshot(); - } -} diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java index eb99be0dc0..4b49c0928b 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java @@ -11,7 +11,6 @@ import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithName; @@ -20,41 +19,32 @@ import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToDocu import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import io.netty.channel.ChannelFuture; import java.io.IOException; -import java.io.InputStream; +import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; -import java.util.Collection; +import java.net.SocketAddress; +import java.util.Collections; import java.util.List; import java.util.Set; import javax.management.InstanceNotFoundException; import javax.management.Notification; import javax.management.NotificationListener; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.config.persist.api.Persister; import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification; -import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession; -import org.opendaylight.controller.netconf.client.NetconfClientDispatcher; -import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; import org.opendaylight.controller.netconf.client.test.TestingNetconfClient; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; -import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher; import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl; import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl; import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService; import org.opendaylight.controller.netconf.mapping.api.Capability; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory; import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator; import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService; import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler; @@ -65,64 +55,48 @@ import org.xml.sax.SAXException; public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { - private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023); + public static final int PORT = 12026; + private static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT); - private NetconfClientDispatcher clientDispatcher; - private DefaultCommitNotificationProducer commitNotifier; + private NetconfMonitoringServiceImpl netconfMonitoringService; - @Before - public void setUp() throws Exception { - super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,NetconfITTest.FACTORIES)); - - NetconfMonitoringServiceImpl monitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider()); - - NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl(); - factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore())); - factoriesListener - .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( - new NetconfMonitoringOperationService(monitoringService))); - - - commitNotifier = new DefaultCommitNotificationProducer(platformMBeanServer); - NetconfServerDispatcher dispatch = createDispatcher(factoriesListener, mockSessionMonitoringService(), commitNotifier); - ChannelFuture s = dispatch.createServer(tcpAddress); - s.await(); - - clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer()); + @Override + protected void setUpTestInitial() { + netconfMonitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider()); } - @After - public void cleanUp(){ - commitNotifier.close(); + @Override + protected SessionMonitoringService getNetconfMonitoringService() throws Exception { + return netconfMonitoringService; } - private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException { - final Collection yangDependencies = NetconfITTest.getBasicYangs(); - return new HardcodedYangStoreService(yangDependencies); + @Override + protected SocketAddress getTcpServerAddress() { + return TCP_ADDRESS; } - - protected SessionMonitoringService mockSessionMonitoringService() { - SessionMonitoringService mockedSessionMonitor = mock(SessionMonitoringService.class); - doNothing().when(mockedSessionMonitor).onSessionUp(any(NetconfManagementSession.class)); - doNothing().when(mockedSessionMonitor).onSessionDown(any(NetconfManagementSession.class)); - return mockedSessionMonitor; + @Override + protected Iterable getAdditionalServiceFactories() { + return Collections.singletonList(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( + new NetconfMonitoringOperationService(netconfMonitoringService))); } - + @Override + protected DefaultCommitNotificationProducer getNotificationProducer() { + return new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer()); + } @Test public void testNetconfCommitNotifications() throws Exception { + final VerifyingNotificationListener notificationVerifier = createCommitNotificationListener(); + final VerifyingPersister mockedAggregator = mockAggregator(); - VerifyingNotificationListener notificationVerifier = createCommitNotificationListener(); - VerifyingPersister mockedAggregator = mockAggregator(); - - try (TestingNetconfClient persisterClient = new TestingNetconfClient("persister", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) { + try (TestingNetconfClient persisterClient = new TestingNetconfClient("persister", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) { try (ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler( platformMBeanServer, mockedAggregator)) { - try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) { + try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) { NetconfMessage response = netconfClient.sendMessage(loadGetConfigMessage()); assertContainsElementWithName(response.getDocument(), "modules"); assertContainsElementWithName(response.getDocument(), "services"); @@ -152,7 +126,7 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { } private VerifyingNotificationListener createCommitNotificationListener() throws InstanceNotFoundException { - VerifyingNotificationListener listener = new VerifyingNotificationListener(); + final VerifyingNotificationListener listener = new VerifyingNotificationListener(); platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.OBJECT_NAME, listener, null, null); return listener; } @@ -171,12 +145,12 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { public NetconfOperationProvider getNetconfOperationProvider() { - NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class); - NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); - NetconfOperationService service = mock(NetconfOperationService.class); - Set caps = Sets.newHashSet(); + final NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class); + final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); + final NetconfOperationService service = mock(NetconfOperationService.class); + final Set caps = Sets.newHashSet(); doReturn(caps).when(service).getCapabilities(); - Set services = Sets.newHashSet(service); + final Set services = Sets.newHashSet(service); doReturn(services).when(snap).getServices(); doReturn(snap).when(factoriesListener).openSnapshot(anyString()); @@ -187,23 +161,23 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { public List notifications = Lists.newArrayList(); @Override - public void handleNotification(Notification notification, Object handback) { + public void handleNotification(final Notification notification, final Object handback) { this.notifications.add(notification); } - void assertNotificationCount(Object size) { + void assertNotificationCount(final Object size) { assertEquals(size, notifications.size()); } - void assertNotificationContent(int notificationIndex, int expectedModulesSize, int expectedServicesSize, int expectedCapsSize) { - Notification notification = notifications.get(notificationIndex); + void assertNotificationContent(final int notificationIndex, final int expectedModulesSize, final int expectedServicesSize, final int expectedCapsSize) { + final Notification notification = notifications.get(notificationIndex); assertEquals(CommitJMXNotification.class, notification.getClass()); - int capsSize = ((CommitJMXNotification) notification).getCapabilities().size(); + final int capsSize = ((CommitJMXNotification) notification).getCapabilities().size(); assertEquals("Expected capabilities count", expectedCapsSize, capsSize); - Element configSnapshot = ((CommitJMXNotification) notification).getConfigSnapshot(); - int modulesSize = configSnapshot.getElementsByTagName("module").getLength(); + final Element configSnapshot = ((CommitJMXNotification) notification).getConfigSnapshot(); + final int modulesSize = configSnapshot.getElementsByTagName("module").getLength(); assertEquals("Expected modules count", expectedModulesSize, modulesSize); - int servicesSize = configSnapshot.getElementsByTagName("instance").getLength(); + final int servicesSize = configSnapshot.getElementsByTagName("instance").getLength(); assertEquals("Expected services count", expectedServicesSize, servicesSize); } } @@ -214,12 +188,12 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { private Persister mockedPersister; public VerifyingPersister() throws IOException { - Persister mockedAggregator = mock(Persister.class); + final Persister mockedAggregator = mock(Persister.class); doAnswer(new Answer() { @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ConfigSnapshotHolder configSnapshot = (ConfigSnapshotHolder) invocation.getArguments()[0]; + public Object answer(final InvocationOnMock invocation) throws Throwable { + final ConfigSnapshotHolder configSnapshot = (ConfigSnapshotHolder) invocation.getArguments()[0]; snapshots.add(configSnapshot); return null; } @@ -228,22 +202,22 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { this.mockedPersister = mockedAggregator; } - void assertSnapshotCount(Object size) { + void assertSnapshotCount(final Object size) { assertEquals(size, snapshots.size()); } - void assertSnapshotContent(int notificationIndex, int expectedModulesSize, int expectedServicesSize, int expectedCapsSize) + void assertSnapshotContent(final int notificationIndex, final int expectedModulesSize, final int expectedServicesSize, final int expectedCapsSize) throws SAXException, IOException { - ConfigSnapshotHolder snapshot = snapshots.get(notificationIndex); - int capsSize = snapshot.getCapabilities().size(); + final ConfigSnapshotHolder snapshot = snapshots.get(notificationIndex); + final int capsSize = snapshot.getCapabilities().size(); assertEquals("Expected capabilities count", expectedCapsSize, capsSize); - Document configSnapshot = readXmlToDocument(snapshot.getConfigSnapshot()); + final Document configSnapshot = readXmlToDocument(snapshot.getConfigSnapshot()); assertElementsCount(configSnapshot, "module", expectedModulesSize); assertElementsCount(configSnapshot, "instance", expectedServicesSize); } @Override - public void persistConfig(ConfigSnapshotHolder configSnapshotHolder) throws IOException { + public void persistConfig(final ConfigSnapshotHolder configSnapshotHolder) throws IOException { mockedPersister.persistConfig(configSnapshotHolder); } diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITMonitoringTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITMonitoringTest.java new file mode 100644 index 0000000000..72a2f8f7ac --- /dev/null +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITMonitoringTest.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.netconf.it; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText; + +import com.google.common.base.Charsets; +import com.google.common.base.Optional; +import com.google.common.collect.Sets; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import org.junit.Test; +import org.opendaylight.controller.netconf.api.NetconfMessage; +import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession; +import org.opendaylight.controller.netconf.client.test.TestingNetconfClient; +import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl; +import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl; +import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService; +import org.opendaylight.controller.netconf.mapping.api.Capability; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory; +import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator; +import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService; +import org.opendaylight.controller.netconf.util.test.XmlFileLoader; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; +import org.slf4j.Logger; +import org.w3c.dom.Document; + +public class NetconfITMonitoringTest extends AbstractNetconfConfigTest { + + public static final int PORT = 12025; + public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT); + public static final TestingCapability TESTING_CAPABILITY = new TestingCapability(); + + private NetconfMonitoringServiceImpl netconfMonitoringService; + + @Override + protected void setUpTestInitial() { + netconfMonitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider()); + } + + @Override + protected SessionMonitoringService getNetconfMonitoringService() throws Exception { + return netconfMonitoringService; + } + + @Override + protected Iterable getAdditionalServiceFactories() { + return Collections.singletonList(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( + new NetconfMonitoringOperationService(netconfMonitoringService))); + } + + @Override + protected InetSocketAddress getTcpServerAddress() { + return TCP_ADDRESS; + } + + static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) { + return new SessionMonitoringService() { + @Override + public void onSessionUp(final NetconfManagementSession session) { + logger.debug("Management session up {}", session); + monitor.onSessionUp(session); + } + + @Override + public void onSessionDown(final NetconfManagementSession session) { + logger.debug("Management session down {}", session); + monitor.onSessionDown(session); + } + }; + } + + @Test + public void testGetResponseFromMonitoring() throws Exception { + try (TestingNetconfClient netconfClient = new TestingNetconfClient("client-monitoring", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 10000))) { + try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("client-monitoring2", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 10000))) { + Thread.sleep(500); + final NetconfMessage response = netconfClient2.sendMessage(getGet()); + assertSessionElementsInResponse(response.getDocument(), 2); + } + Thread.sleep(500); + final NetconfMessage response = netconfClient.sendMessage(getGet()); + assertSessionElementsInResponse(response.getDocument(), 1); + } + } + + + @Test(timeout = 13 * 10000) + public void testClientHelloWithAuth() throws Exception { + String fileName = "netconfMessages/client_hello_with_auth.xml"; + final String hello = XmlFileLoader.fileToString(fileName); + + fileName = "netconfMessages/get.xml"; + final String get = XmlFileLoader.fileToString(fileName); + + final Socket sock = new Socket(TCP_ADDRESS.getHostName(), TCP_ADDRESS.getPort()); + sock.getOutputStream().write(hello.getBytes(Charsets.UTF_8)); + final String separator = "]]>]]>"; + + sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8)); + sock.getOutputStream().write(get.getBytes(Charsets.UTF_8)); + sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8)); + + final StringBuilder responseBuilder = new StringBuilder(); + + try (InputStream inputStream = sock.getInputStream(); + InputStreamReader reader = new InputStreamReader(inputStream); + BufferedReader buff = new BufferedReader(reader)) { + String line; + while ((line = buff.readLine()) != null) { + + responseBuilder.append(line); + responseBuilder.append(System.lineSeparator()); + + if(line.contains("")) + break; + } + } + + sock.close(); + + final String helloMsg = responseBuilder.substring(0, responseBuilder.indexOf(separator)); + Document doc = XmlUtil.readXmlToDocument(helloMsg); + assertContainsElementWithText(doc, "urn:ietf:params:netconf:capability:candidate:1.0"); + + final String replyMsg = responseBuilder.substring(responseBuilder.indexOf(separator) + separator.length()); + doc = XmlUtil.readXmlToDocument(replyMsg); + assertContainsElementWithText(doc, "tomas"); + } + + private void assertSessionElementsInResponse(final Document document, final int i) { + final int elementSize = document.getElementsByTagName("session-id").getLength(); + assertEquals("Incorrect number of session-id tags in " + XmlUtil.toString(document), i, elementSize); + } + + public static NetconfOperationProvider getNetconfOperationProvider() { + final NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class); + final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); + try { + doNothing().when(snap).close(); + } catch (final Exception e) { + // not happening + throw new IllegalStateException(e); + } + final NetconfOperationService service = mock(NetconfOperationService.class); + final Set caps = Sets.newHashSet(); + caps.add(TESTING_CAPABILITY); + + doReturn(caps).when(service).getCapabilities(); + final Set services = Sets.newHashSet(service); + doReturn(services).when(snap).getServices(); + doReturn(snap).when(factoriesListener).openSnapshot(anyString()); + + return factoriesListener; + } + + private static class TestingCapability implements Capability { + @Override + public String getCapabilityUri() { + return "namespaceModuleRevision"; + } + + @Override + public Optional getModuleNamespace() { + return Optional.of("namespace"); + } + + @Override + public Optional getModuleName() { + return Optional.of("name"); + } + + @Override + public Optional getRevision() { + return Optional.of("revision"); + } + + @Override + public Optional getCapabilitySchema() { + return Optional.of("content"); + } + + @Override + public Optional> getLocation() { + return Optional.absent(); + } + } +} diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java index e5e34548b3..67ccf0c02c 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java @@ -8,27 +8,25 @@ package org.opendaylight.controller.netconf.it; -import static java.util.Arrays.asList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import com.google.common.collect.Lists; +import io.netty.channel.local.LocalAddress; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; +import io.netty.util.concurrent.GlobalEventExecutor; import java.io.IOException; -import java.io.InputStream; -import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; -import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.Assert; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; -import org.opendaylight.controller.config.spi.ModuleFactory; import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.netconf.auth.AuthProvider; import org.opendaylight.controller.netconf.client.NetconfClientDispatcher; @@ -37,87 +35,44 @@ import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionList import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder; import org.opendaylight.controller.netconf.client.test.TestingNetconfClient; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; -import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; -import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword; import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator; import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil; -import org.opendaylight.controller.netconf.util.test.XmlFileLoader; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.opendaylight.protocol.framework.NeverReconnectStrategy; -import com.google.common.collect.Lists; - -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; -import io.netty.util.concurrent.GlobalEventExecutor; - public class NetconfITSecureTest extends AbstractNetconfConfigTest { - private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024); + public static final int PORT = 12024; + private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pwd"; - private DefaultCommitNotificationProducer commitNot; private NetconfSSHServer sshServer; - private NetconfMessage getConfig; @Before public void setUp() throws Exception { - this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml"); - - super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, getModuleFactories().toArray( - new ModuleFactory[0]))); - - final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl(); - factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore())); - - commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer()); - - - final NetconfServerDispatcher dispatchS = createDispatcher(factoriesListener); - ChannelFuture s = dispatchS.createLocalServer(NetconfConfigUtil.getNetconfLocalAddress()); - s.await(); - EventLoopGroup bossGroup = new NioEventLoopGroup(); - final char[] pem = PEMGenerator.generate().toCharArray(); - sshServer = NetconfSSHServer.start(tlsAddress.getPort(), NetconfConfigUtil.getNetconfLocalAddress(), bossGroup, pem); + sshServer = NetconfSSHServer.start(TLS_ADDRESS.getPort(), NetconfConfigUtil.getNetconfLocalAddress(), getNettyThreadgroup(), pem); sshServer.setAuthProvider(getAuthProvider()); } - private NetconfServerDispatcher createDispatcher(final NetconfOperationServiceFactoryListenerImpl factoriesListener) { - return super.createDispatcher(factoriesListener, NetconfITTest.getNetconfMonitoringListenerService(), commitNot); - } - @After public void tearDown() throws Exception { sshServer.close(); - commitNot.close(); sshServer.join(); } - private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException { - final Collection yangDependencies = NetconfITTest.getBasicYangs(); - return new HardcodedYangStoreService(yangDependencies); - } - - protected List getModuleFactories() { - return asList(NetconfITTest.FACTORIES); - } - @Test public void testSecure() throws Exception { final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer()); try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration())) { - NetconfMessage response = netconfClient.sendMessage(getConfig); - Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()), + NetconfMessage response = netconfClient.sendMessage(getGetConfig()); + assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()), NetconfMessageUtil.isErrorMessage(response)); final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("\n")); response = netconfClient.sendMessage(gs); - Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()), + assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()), NetconfMessageUtil.isErrorMessage(response)); } } @@ -146,7 +101,7 @@ public class NetconfITSecureTest extends AbstractNetconfConfigTest { final int requests = 1000; for (int i = 0; i < requests; i++) { - final Future netconfMessageFuture = netconfClient.sendRequest(getConfig); + final Future netconfMessageFuture = netconfClient.sendRequest(getGetConfig()); futures.add(netconfMessageFuture); netconfMessageFuture.addListener(new GenericFutureListener>() { @Override @@ -164,13 +119,13 @@ public class NetconfITSecureTest extends AbstractNetconfConfigTest { // Give future listeners some time to finish counter incrementation Thread.sleep(5000); - org.junit.Assert.assertEquals(requests, responseCounter.get()); + assertEquals(requests, responseCounter.get()); } } public NetconfClientConfiguration getClientConfiguration() throws IOException { final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create(); - b.withAddress(tlsAddress); + b.withAddress(TLS_ADDRESS); b.withSessionListener(new SimpleNetconfClientSessionListener()); b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000)); b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH); @@ -180,12 +135,18 @@ public class NetconfITSecureTest extends AbstractNetconfConfigTest { } public AuthProvider getAuthProvider() throws Exception { - AuthProvider mock = mock(AuthProvider.class); - doReturn(true).when(mock).authenticated(anyString(), anyString()); - return mock; + final AuthProvider mockAuth = mock(AuthProvider.class); + doReturn("mockedAuth").when(mockAuth).toString(); + doReturn(true).when(mockAuth).authenticated(anyString(), anyString()); + return mockAuth; } public AuthenticationHandler getAuthHandler() throws IOException { - return new LoginPassword("user", "pwd"); + return new LoginPassword(USERNAME, PASSWORD); + } + + @Override + protected LocalAddress getTcpServerAddress() { + return NetconfConfigUtil.getNetconfLocalAddress(); } } diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java index 8e69e6a345..a7a9d7494a 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java @@ -8,11 +8,11 @@ package org.opendaylight.controller.netconf.it; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -20,15 +20,8 @@ import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import io.netty.channel.ChannelFuture; import java.io.IOException; -import java.io.InputStream; -import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -36,35 +29,19 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import javax.management.ObjectName; import javax.xml.parsers.ParserConfigurationException; -import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -import org.junit.matchers.JUnitMatchers; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; -import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; -import org.opendaylight.controller.config.spi.ModuleFactory; import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory; -import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory; import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory; import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean; import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory; import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean; -import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.api.NetconfMessage; -import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; +import org.opendaylight.controller.netconf.client.NetconfClientDispatcher; import org.opendaylight.controller.netconf.client.test.TestingNetconfClient; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; -import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; -import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher; -import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; import org.opendaylight.controller.netconf.util.test.XmlFileLoader; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; @@ -80,129 +57,57 @@ import org.xml.sax.SAXException; public class NetconfITTest extends AbstractNetconfConfigTest { - // TODO refactor, pull common code up to AbstractNetconfITTest + public static final int PORT = 12023; + public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT); - private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023); - - - private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession; - private DefaultCommitNotificationProducer commitNotificationProducer; - private NetconfServerDispatcher dispatch; - - private NetconfClientDispatcherImpl clientDispatcher; - - static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(), new DepTestImplModuleFactory(), - new NetconfTestImplModuleFactory(), new IdentityTestModuleFactory(), - new MultipleDependenciesModuleFactory()}; + private NetconfMessage getConfigCandidate, editConfig, closeSession; + private NetconfClientDispatcher clientDispatcher; @Before public void setUp() throws Exception { - initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, - FACTORIES - )); - loadMessages(); - - NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl(); - factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore())); - - commitNotificationProducer = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer()); - - dispatch = createDispatcher(factoriesListener); - ChannelFuture s = dispatch.createServer(tcpAddress); - s.await(); - - clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer()); - } - - private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) { - return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNotificationProducer); + clientDispatcher = getClientDispatcher(); } - static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() { - NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class); - NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); - doReturn(Collections.emptySet()).when(snap).getServices(); - doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString()); - return new NetconfMonitoringServiceImpl(netconfOperationProvider); - } - - @After - public void tearDown() throws Exception { - commitNotificationProducer.close(); - clientDispatcher.close(); + @Override + protected InetSocketAddress getTcpServerAddress() { + return TCP_ADDRESS; } private void loadMessages() throws IOException, SAXException, ParserConfigurationException { this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml"); - this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml"); this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml"); this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml"); } - private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException { - final Collection yangDependencies = getBasicYangs(); - return new HardcodedYangStoreService(yangDependencies); - } - - static Collection getBasicYangs() throws IOException { - - List paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang", - "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang", - "/META-INF/yang/ietf-inet-types.yang"); - final Collection yangDependencies = new ArrayList<>(); - List failedToFind = new ArrayList<>(); - for (String path : paths) { - InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path); - if (resourceAsStream == null) { - failedToFind.add(path); - } else { - yangDependencies.add(resourceAsStream); - } - } - assertEquals("Some yang files were not found", Collections.emptyList(), failedToFind); - return yangDependencies; - } - - @Test public void testNetconfClientDemonstration() throws Exception { - try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) { + try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 4000))) { - Set capabilitiesFromNetconfServer = netconfClient.getCapabilities(); - long sessionId = netconfClient.getSessionId(); + final Set capabilitiesFromNetconfServer = netconfClient.getCapabilities(); + final long sessionId = netconfClient.getSessionId(); // NetconfMessage can be created : // new NetconfMessage(XmlUtil.readXmlToDocument("")); - NetconfMessage response = netconfClient.sendMessage(getConfig); + final NetconfMessage response = netconfClient.sendMessage(getGetConfig()); response.getDocument(); } } @Test public void testTwoSessions() throws Exception { - try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", clientDispatcher, getClientConfiguration(tcpAddress, 10000))) { - try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", clientDispatcher, getClientConfiguration(tcpAddress, 10000))) { + try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000))) { + try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000))) { assertNotNull(netconfClient2.getCapabilities()); } } } - @Ignore - @Test - public void waitingTest() throws Exception { - final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction(); - transaction.createModule(DepTestImplModuleFactory.NAME, "eb"); - transaction.commit(); - Thread.currentThread().suspend(); - } - @Test public void rpcReplyContainsAllAttributesTest() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { - final String rpc = "" - + "" + ""; + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { + final String rpc = "" + ""; final Document doc = XmlUtil.readXmlToDocument(rpc); final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc)); assertNotNull(message); @@ -228,9 +133,8 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void rpcReplyErrorContainsAllAttributesTest() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { - final String rpc = "" - + "" + ""; + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { + final String rpc = "" + ""; final Document doc = XmlUtil.readXmlToDocument(rpc); final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc)); final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes(); @@ -243,16 +147,16 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void rpcOutputContainsCorrectNamespace() throws Exception { final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction(); - ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD"); - ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance"); - NetconfTestImplModuleMXBean proxy = configRegistryClient + final ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD"); + final ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance"); + final NetconfTestImplModuleMXBean proxy = configRegistryClient .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class); proxy.setTestingDep(dep); proxy.setSimpleShort((short) 0); transaction.commit(); - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl"; final String rpc = "" @@ -275,7 +179,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void testCloseSession() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { // edit config Document rpcReply = netconfClient.sendMessage(this.editConfig) @@ -291,7 +195,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void testEditConfig() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { // send edit_config.xml final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument(); assertIsOK(rpcReply); @@ -300,7 +204,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void testValidate() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { // begin transaction Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument(); assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName()); @@ -318,7 +222,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest { } private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException { - return assertGetConfigWorks(netconfClient, this.getConfig); + return assertGetConfigWorks(netconfClient, getGetConfig()); } private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage) @@ -331,14 +235,14 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void testGetConfig() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { assertGetConfigWorks(netconfClient); } } @Test public void createYangTestBasedOnYuma() throws Exception { - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { Document rpcReply = netconfClient.sendMessage( XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml")) .getDocument(); @@ -351,7 +255,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest { final ObjectName on = new ObjectName( "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep"); - Set cfgBeans = configRegistryClient.lookupConfigBeans(); + final Set cfgBeans = configRegistryClient.lookupConfigBeans(); assertEquals(cfgBeans, Sets.newHashSet(on)); } } @@ -364,21 +268,21 @@ public class NetconfITTest extends AbstractNetconfConfigTest { @Test public void testIdRef() throws Exception { - NetconfMessage editId = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_identities.xml"); - NetconfMessage commit = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"); + final NetconfMessage editId = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_identities.xml"); + final NetconfMessage commit = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"); - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { assertIsOK(netconfClient.sendMessage(editId).getDocument()); assertIsOK(netconfClient.sendMessage(commit).getDocument()); - NetconfMessage response = netconfClient.sendMessage(getConfig); + final NetconfMessage response = netconfClient.sendMessage(getGetConfig()); - assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("prefix:test-identity1")); - assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("prefix:test-identity2")); - assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("prefix:test-identity2")); - assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("prefix:test-identity1")); + assertThat(XmlUtil.toString(response.getDocument()), containsString("prefix:test-identity1")); + assertThat(XmlUtil.toString(response.getDocument()), containsString("prefix:test-identity2")); + assertThat(XmlUtil.toString(response.getDocument()), containsString("prefix:test-identity2")); + assertThat(XmlUtil.toString(response.getDocument()), containsString("prefix:test-identity1")); - } catch (Exception e) { + } catch (final Exception e) { fail(Throwables.getStackTraceAsString(e)); } } @@ -394,25 +298,24 @@ public class NetconfITTest extends AbstractNetconfConfigTest { return ret; } - @Test public void testMultipleDependencies() throws Exception { // push first xml, should add parent and d1,d2 dependencies - try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) { - Document rpcReply = netconfClient.sendMessage( + try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) { + final Document rpcReply = netconfClient.sendMessage( XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps1.xml")) .getDocument(); assertIsOK(rpcReply); commit(netconfClient); } // verify that parent.getTestingDeps == d1,d2 - MultipleDependenciesModuleMXBean parentProxy = configRegistryClient.newMXBeanProxy( + final MultipleDependenciesModuleMXBean parentProxy = configRegistryClient.newMXBeanProxy( configRegistryClient.lookupConfigBean(MultipleDependenciesModuleFactory.NAME, "parent"), MultipleDependenciesModuleMXBean.class); { - List testingDeps = parentProxy.getTestingDeps(); + final List testingDeps = parentProxy.getTestingDeps(); assertEquals(2, testingDeps.size()); - Set actualRefs = getServiceReferences(testingDeps); + final Set actualRefs = getServiceReferences(testingDeps); assertEquals(Sets.newHashSet("ref_d1", "ref_d2"), actualRefs); } @@ -422,35 +325,35 @@ public class NetconfITTest extends AbstractNetconfConfigTest { mergeD3(parentProxy); } - public void mergeD3(MultipleDependenciesModuleMXBean parentProxy) throws Exception { + public void mergeD3(final MultipleDependenciesModuleMXBean parentProxy) throws Exception { try (TestingNetconfClient netconfClient = new TestingNetconfClient( - "test " + tcpAddress.toString(), clientDispatcher, getClientConfiguration(tcpAddress, 5000))) { + "test " + TCP_ADDRESS.toString(), clientDispatcher, getClientConfiguration(TCP_ADDRESS, 5000))) { - Document rpcReply = netconfClient.sendMessage( + final Document rpcReply = netconfClient.sendMessage( XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps2.xml")) .getDocument(); assertIsOK(rpcReply); commit(netconfClient); } { - List testingDeps = parentProxy.getTestingDeps(); + final List testingDeps = parentProxy.getTestingDeps(); assertEquals(3, testingDeps.size()); - Set actualRefs = getServiceReferences(testingDeps); + final Set actualRefs = getServiceReferences(testingDeps); assertEquals(Sets.newHashSet("ref_d1", "ref_d2", "ref_d3"), actualRefs); } } - public Set getServiceReferences(List testingDeps) { + public Set getServiceReferences(final List testingDeps) { return new HashSet<>(Lists.transform(testingDeps, new Function() { @Override - public String apply(ObjectName input) { + public String apply(final ObjectName input) { return ObjectNameUtil.getReferenceName(input); } })); } - public void commit(TestingNetconfClient netconfClient) throws Exception { - Document rpcReply; + public void commit(final TestingNetconfClient netconfClient) throws Exception { + final Document rpcReply; rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml")) .getDocument(); assertIsOK(rpcReply); diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java deleted file mode 100644 index 05e32577fe..0000000000 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.it; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText; - -import com.google.common.base.Charsets; -import com.google.common.base.Optional; -import com.google.common.collect.Sets; -import io.netty.channel.ChannelFuture; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import junit.framework.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver; -import org.opendaylight.controller.netconf.api.NetconfMessage; -import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession; -import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; -import org.opendaylight.controller.netconf.client.test.TestingNetconfClient; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl; -import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException; -import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; -import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher; -import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl; -import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl; -import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService; -import org.opendaylight.controller.netconf.mapping.api.Capability; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; -import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator; -import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService; -import org.opendaylight.controller.netconf.util.test.XmlFileLoader; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -public class NetconfMonitoringITTest extends AbstractNetconfConfigTest { - - private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class); - - private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023); - - @Mock - private DefaultCommitNotificationProducer commitNot; - private NetconfServerDispatcher dispatch; - - private NetconfClientDispatcherImpl clientDispatcher; - - private NetconfMonitoringServiceImpl monitoringService; - - @Before - public void setUp() throws Exception { - super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, NetconfITTest.FACTORIES)); - - monitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider()); - - NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl(); - factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore())); - factoriesListener - .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( - new NetconfMonitoringOperationService(monitoringService))); - - - dispatch = createDispatcher(factoriesListener); - ChannelFuture s = dispatch.createServer(tcpAddress); - s.await(); - - clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer()); - } - - private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException { - final Collection yangDependencies = NetconfITTest.getBasicYangs(); - return new HardcodedYangStoreService(yangDependencies); - } - - private NetconfServerDispatcher createDispatcher( - NetconfOperationServiceFactoryListenerImpl factoriesListener) { - return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(logger, monitoringService), commitNot); - } - - static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) { - return new SessionMonitoringService() { - @Override - public void onSessionUp(NetconfManagementSession session) { - logger.debug("Management session up {}", session); - monitor.onSessionUp(session); - } - - @Override - public void onSessionDown(NetconfManagementSession session) { - logger.debug("Management session down {}", session); - monitor.onSessionDown(session); - } - }; - } - - - @Test - public void testGetResponseFromMonitoring() throws Exception { - try (TestingNetconfClient netconfClient = new TestingNetconfClient("client-monitoring", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) { - try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("client-monitoring2", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) { - NetconfMessage response = netconfClient.sendMessage(loadGetMessage()); - assertSessionElementsInResponse(response.getDocument(), 2); - } - NetconfMessage response = netconfClient.sendMessage(loadGetMessage()); - assertSessionElementsInResponse(response.getDocument(), 1); - } - } - - - @Test(timeout = 13 * 10000) - public void testClientHelloWithAuth() throws Exception { - String fileName = "netconfMessages/client_hello_with_auth.xml"; - String hello = XmlFileLoader.fileToString(fileName); - - fileName = "netconfMessages/get.xml"; - String get = XmlFileLoader.fileToString(fileName); - - Socket sock = new Socket(tcpAddress.getHostName(), tcpAddress.getPort()); - sock.getOutputStream().write(hello.getBytes(Charsets.UTF_8)); - String separator = "]]>]]>"; - - sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8)); - sock.getOutputStream().write(get.getBytes(Charsets.UTF_8)); - sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8)); - - StringBuilder responseBuilder = new StringBuilder(); - - try (InputStream inputStream = sock.getInputStream(); - InputStreamReader reader = new InputStreamReader(inputStream); - BufferedReader buff = new BufferedReader(reader)) { - String line; - while ((line = buff.readLine()) != null) { - - responseBuilder.append(line); - responseBuilder.append(System.lineSeparator()); - - if(line.contains("")) - break; - } - } - - sock.close(); - - String helloMsg = responseBuilder.substring(0, responseBuilder.indexOf(separator)); - Document doc = XmlUtil.readXmlToDocument(helloMsg); - assertContainsElementWithText(doc, "urn:ietf:params:netconf:capability:candidate:1.0"); - - String replyMsg = responseBuilder.substring(responseBuilder.indexOf(separator) + separator.length()); - doc = XmlUtil.readXmlToDocument(replyMsg); - assertContainsElementWithText(doc, "tomas"); - } - - private void assertSessionElementsInResponse(Document document, int i) { - int elementSize = document.getElementsByTagName("session-id").getLength(); - Assert.assertEquals("Incorrect number of session-id tags in " + XmlUtil.toString(document),i, elementSize); - } - - private NetconfMessage loadGetMessage() throws Exception { - return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml"); - } - - public static NetconfOperationProvider getNetconfOperationProvider() throws Exception { - NetconfOperationProvider factoriesListener = mock(NetconfOperationProvider.class); - NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class); - doNothing().when(snap).close(); - NetconfOperationService service = mock(NetconfOperationService.class); - Set caps = Sets.newHashSet(); - caps.add(new Capability() { - @Override - public String getCapabilityUri() { - return "namespaceModuleRevision"; - } - - @Override - public Optional getModuleNamespace() { - return Optional.of("namespace"); - } - - @Override - public Optional getModuleName() { - return Optional.of("name"); - } - - @Override - public Optional getRevision() { - return Optional.of("revision"); - } - - @Override - public Optional getCapabilitySchema() { - return Optional.of("content"); - } - - @Override - public Optional> getLocation() { - return Optional.absent(); - } - }); - - doReturn(caps).when(service).getCapabilities(); - Set services = Sets.newHashSet(service); - doReturn(services).when(snap).getServices(); - doReturn(snap).when(factoriesListener).openSnapshot(anyString()); - - return factoriesListener; - } - - -} diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/SSLUtil.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/SSLUtil.java index 4d232a619a..f76bf4f4c3 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/SSLUtil.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/SSLUtil.java @@ -24,8 +24,7 @@ import com.google.common.base.Preconditions; public final class SSLUtil { - private SSLUtil() { - } + private SSLUtil() {} public static SSLContext initializeSecureContext(final String pass, final InputStream ksKeysFile, final InputStream ksTrustFile, final String algorithm) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,