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