Remove System.out from netconf tests
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfMonitoringITTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.netconf.it;
9
10 import com.google.common.base.Charsets;
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Sets;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.channel.EventLoopGroup;
15 import io.netty.channel.nio.NioEventLoopGroup;
16 import io.netty.util.HashedWheelTimer;
17 import junit.framework.Assert;
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.junit.matchers.JUnitMatchers;
21 import org.mockito.Mock;
22 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
23 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
24 import org.opendaylight.controller.config.spi.ModuleFactory;
25 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
26 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
27 import org.opendaylight.controller.netconf.api.NetconfMessage;
28 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
29 import org.opendaylight.controller.netconf.client.NetconfClient;
30 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
31 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
32 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
33 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
34 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
35 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
36 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
37 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
38 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
39 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
40 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
41 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
42 import org.opendaylight.controller.netconf.mapping.api.Capability;
43 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
44 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
45 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
46 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50
51 import java.io.BufferedReader;
52 import java.io.IOException;
53 import java.io.InputStream;
54 import java.io.InputStreamReader;
55 import java.net.InetSocketAddress;
56 import java.net.Socket;
57 import java.util.Collection;
58 import java.util.List;
59 import java.util.Set;
60 import java.util.concurrent.TimeUnit;
61
62 import static org.mockito.Matchers.anyLong;
63 import static org.mockito.Mockito.doReturn;
64 import static org.mockito.Mockito.mock;
65
66 public class NetconfMonitoringITTest extends AbstractConfigTest {
67
68     private static final Logger logger =  LoggerFactory.getLogger(NetconfITTest.class);
69
70     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
71
72     @Mock
73     private DefaultCommitNotificationProducer commitNot;
74     private NetconfServerDispatcher dispatch;
75     private EventLoopGroup nettyThreadgroup;
76
77     private NetconfClientDispatcher clientDispatcher;
78
79     private NetconfMonitoringServiceImpl monitoringService;
80
81     @Before
82     public void setUp() throws Exception {
83         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(NetconfITTest.getModuleFactoriesS().toArray(
84                 new ModuleFactory[0])));
85
86         monitoringService = new NetconfMonitoringServiceImpl(getFactoriesListener());
87
88         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
89         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
90         factoriesListener
91                 .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
92                         new NetconfMonitoringOperationService(monitoringService)));
93
94         nettyThreadgroup = new NioEventLoopGroup();
95
96         dispatch = createDispatcher(factoriesListener);
97         ChannelFuture s = dispatch.createServer(tcpAddress);
98         s.await();
99
100         clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup);
101     }
102
103     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
104         final Collection<InputStream> yangDependencies = NetconfITTest.getBasicYangs();
105         return new HardcodedYangStoreService(yangDependencies);
106     }
107
108     private NetconfServerDispatcher createDispatcher(
109                                                      NetconfOperationServiceFactoryListenerImpl factoriesListener) {
110         SessionIdProvider idProvider = new SessionIdProvider();
111         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
112                 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
113
114         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
115                 factoriesListener, commitNot, idProvider, getNetconfMonitoringListenerService(logger, monitoringService));
116
117         NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
118                 serverNegotiatorFactory, listenerFactory);
119         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
120     }
121
122     static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) {
123         return new SessionMonitoringService() {
124             @Override
125             public void onSessionUp(NetconfManagementSession session) {
126                 logger.debug("Management session up {}", session);
127                 monitor.onSessionUp(session);
128             }
129
130             @Override
131             public void onSessionDown(NetconfManagementSession session) {
132                 logger.debug("Management session down {}", session);
133                 monitor.onSessionDown(session);
134             }
135         };
136     }
137
138
139     @Test
140     public void testGetResponseFromMonitoring() throws Exception {
141         try (NetconfClient netconfClient = new NetconfClient("client-monitoring", tcpAddress, 4000, clientDispatcher)) {
142         try (NetconfClient netconfClient2 = new NetconfClient("client-monitoring2", tcpAddress, 4000, clientDispatcher)) {
143             NetconfMessage response = netconfClient.sendMessage(loadGetMessage());
144             assertSessionElementsInResponse(response.getDocument(), 2);
145         }
146             NetconfMessage response = netconfClient.sendMessage(loadGetMessage());
147             assertSessionElementsInResponse(response.getDocument(), 1);
148         }
149     }
150
151
152     @Test(timeout = 5 * 10000)
153     public void testClientHelloWithAuth() throws Exception {
154         String fileName = "netconfMessages/client_hello_with_auth.xml";
155         String hello = XmlFileLoader.fileToString(fileName);
156
157         fileName = "netconfMessages/get.xml";
158         String get = XmlFileLoader.fileToString(fileName);
159
160         Socket sock = new Socket(tcpAddress.getHostName(), tcpAddress.getPort());
161         sock.getOutputStream().write(hello.getBytes(Charsets.UTF_8));
162         String separator = "]]>]]>";
163
164         sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8));
165         sock.getOutputStream().write(get.getBytes(Charsets.UTF_8));
166         sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8));
167
168         StringBuilder responseBuilder = new StringBuilder();
169
170         try (InputStream inputStream = sock.getInputStream();
171              InputStreamReader reader = new InputStreamReader(inputStream);
172              BufferedReader buff = new BufferedReader(reader)) {
173             String line;
174             while ((line = buff.readLine()) != null) {
175
176                 responseBuilder.append(line);
177                 responseBuilder.append(System.lineSeparator());
178
179                 if(line.contains("</rpc-reply>"))
180                     break;
181             }
182         }
183
184         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<capability>urn:ietf:params:netconf:capability:candidate:1.0</capability>"));
185         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<username>tomas</username>"));
186     }
187
188     private void assertSessionElementsInResponse(Document document, int i) {
189         int elementSize = document.getElementsByTagName("session-id").getLength();
190         Assert.assertEquals(i, elementSize);
191     }
192
193     private NetconfMessage loadGetMessage() throws Exception {
194         return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
195     }
196
197     public static NetconfOperationServiceFactoryListener getFactoriesListener() {
198         NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
199         NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
200         NetconfOperationService service = mock(NetconfOperationService.class);
201         Set<Capability> caps = Sets.newHashSet();
202         caps.add(new Capability() {
203             @Override
204             public String getCapabilityUri() {
205                 return "namespaceModuleRevision";
206             }
207
208             @Override
209             public Optional<String> getModuleNamespace() {
210                 return Optional.of("namespace");
211             }
212
213             @Override
214             public Optional<String> getModuleName() {
215                 return Optional.of("name");
216             }
217
218             @Override
219             public Optional<String> getRevision() {
220                 return Optional.of("revision");
221             }
222
223             @Override
224             public Optional<String> getCapabilitySchema() {
225                 return Optional.of("content");
226             }
227
228             @Override
229             public Optional<List<String>> getLocation() {
230                 return Optional.absent();
231             }
232         });
233
234         doReturn(caps).when(service).getCapabilities();
235         Set<NetconfOperationService> services = Sets.newHashSet(service);
236         doReturn(services).when(snap).getServices();
237         doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
238
239         return factoriesListener;
240     }
241
242
243 }