339c7e7dd74d2c6dd74c2f5cf710e705cdb15984
[netconf.git] / protocol / netconf-client / src / test / java / org / opendaylight / netconf / client / TestingNetconfClient.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.netconf.client;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.collect.Sets;
13 import io.netty.channel.nio.NioEventLoopGroup;
14 import io.netty.util.HashedWheelTimer;
15 import io.netty.util.concurrent.Future;
16 import io.netty.util.concurrent.GlobalEventExecutor;
17 import java.io.Closeable;
18 import java.io.IOException;
19 import java.net.InetAddress;
20 import java.net.InetSocketAddress;
21 import java.net.UnknownHostException;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.CancellationException;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.netconf.api.NetconfMessage;
30 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
31 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration.NetconfClientProtocol;
32 import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
33 import org.opendaylight.netconf.nettyutil.NeverReconnectStrategy;
34 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
35 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
37
38 /**
39  * Synchronous netconf client suitable for testing.
40  */
41 public class TestingNetconfClient implements Closeable {
42
43     public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
44
45     private final String label;
46     private final NetconfClientSession clientSession;
47     private final NetconfClientSessionListener sessionListener;
48
49     public TestingNetconfClient(final String clientLabel,
50                                 final NetconfClientDispatcher netconfClientDispatcher,
51                                 final NetconfClientConfiguration config) throws InterruptedException {
52         label = clientLabel;
53         sessionListener = config.getSessionListener();
54         Future<NetconfClientSession> clientFuture = netconfClientDispatcher.createClient(config);
55         clientSession = get(clientFuture);
56     }
57
58     private static NetconfClientSession get(final Future<NetconfClientSession> clientFuture)
59             throws InterruptedException {
60         try {
61             return clientFuture.get();
62         } catch (CancellationException e) {
63             throw new RuntimeException("Cancelling " + TestingNetconfClient.class.getSimpleName(), e);
64         } catch (ExecutionException e) {
65             throw new IllegalStateException("Unable to create " + TestingNetconfClient.class.getSimpleName(), e);
66         }
67     }
68
69     public Future<NetconfMessage> sendRequest(final NetconfMessage message) {
70         return ((SimpleNetconfClientSessionListener) sessionListener).sendRequest(message);
71     }
72
73     public NetconfMessage sendMessage(final NetconfMessage message, final int attemptMsDelay) throws ExecutionException,
74             InterruptedException, TimeoutException {
75         return sendRequest(message).get(attemptMsDelay, TimeUnit.MILLISECONDS);
76     }
77
78     public NetconfMessage sendMessage(final NetconfMessage message) throws ExecutionException,
79             InterruptedException, TimeoutException {
80         return sendMessage(message, DEFAULT_CONNECT_TIMEOUT);
81     }
82
83     @Override
84     public void close() throws IOException {
85         clientSession.close();
86     }
87
88     @Override
89     public String toString() {
90         final StringBuilder sb = new StringBuilder("TestingNetconfClient{");
91         sb.append("label=").append(label);
92         sb.append(", sessionId=").append(sessionId().getValue());
93         sb.append('}');
94         return sb.toString();
95     }
96
97     public @NonNull SessionIdType sessionId() {
98         return clientSession.sessionId();
99     }
100
101     public Set<String> getCapabilities() {
102         checkState(clientSession != null, "Client was not initialized successfully");
103         return Sets.newHashSet(clientSession.getServerCapabilities());
104     }
105
106     public static void main(final String[] args) throws Exception {
107         HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
108         NioEventLoopGroup nettyGroup = new NioEventLoopGroup();
109         NetconfClientDispatcherImpl netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup,
110                 hashedWheelTimer);
111         LoginPasswordHandler authHandler = new LoginPasswordHandler("admin", "admin");
112         TestingNetconfClient client = new TestingNetconfClient("client", netconfClientDispatcher,
113                 getClientConfig("127.0.0.1", 1830, true, Optional.of(authHandler)));
114         System.console().writer().println(client.getCapabilities());
115     }
116
117     private static NetconfClientConfiguration getClientConfig(final String host, final int port, final boolean ssh,
118             final Optional<? extends AuthenticationHandler> maybeAuthHandler) throws UnknownHostException {
119         InetSocketAddress netconfAddress = new InetSocketAddress(InetAddress.getByName(host), port);
120         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
121         b.withAddress(netconfAddress);
122         b.withSessionListener(new SimpleNetconfClientSessionListener());
123         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
124                 NetconfClientConfigurationBuilder.DEFAULT_CONNECTION_TIMEOUT_MILLIS));
125         if (ssh) {
126             b.withProtocol(NetconfClientProtocol.SSH);
127             b.withAuthHandler(maybeAuthHandler.orElseThrow());
128         } else {
129             b.withProtocol(NetconfClientProtocol.TCP);
130         }
131         return b.build();
132     }
133 }