Specialize protocol-framework to netconf
[netconf.git] / netconf / 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
9 package org.opendaylight.netconf.client;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Sets;
14 import io.netty.channel.nio.NioEventLoopGroup;
15 import io.netty.util.HashedWheelTimer;
16 import io.netty.util.concurrent.Future;
17 import io.netty.util.concurrent.GlobalEventExecutor;
18 import java.io.Closeable;
19 import java.io.IOException;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.UnknownHostException;
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.opendaylight.netconf.api.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.NeverReconnectStrategy;
33 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
34 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
35
36
37 /**
38  * Synchronous netconf client suitable for testing.
39  */
40 public class TestingNetconfClient implements Closeable {
41
42     public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
43
44     private final String label;
45     private final NetconfClientSession clientSession;
46     private final NetconfClientSessionListener sessionListener;
47     private final long sessionId;
48
49     public TestingNetconfClient(String clientLabel,
50                                 NetconfClientDispatcher netconfClientDispatcher,
51                                 final NetconfClientConfiguration config) throws InterruptedException {
52         this.label = clientLabel;
53         sessionListener = config.getSessionListener();
54         Future<NetconfClientSession> clientFuture = netconfClientDispatcher.createClient(config);
55         clientSession = get(clientFuture);
56         this.sessionId = clientSession.getSessionId();
57     }
58
59     private static NetconfClientSession get(Future<NetconfClientSession> clientFuture) 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(NetconfMessage message) {
70         return ((SimpleNetconfClientSessionListener) sessionListener).sendRequest(message);
71     }
72
73     public NetconfMessage sendMessage(NetconfMessage message, int attemptMsDelay) throws ExecutionException,
74             InterruptedException, TimeoutException {
75         return sendRequest(message).get(attemptMsDelay, TimeUnit.MILLISECONDS);
76     }
77
78     public NetconfMessage sendMessage(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);
93         sb.append('}');
94         return sb.toString();
95     }
96
97     public long getSessionId() {
98         return sessionId;
99     }
100
101     public Set<String> getCapabilities() {
102         Preconditions.checkState(clientSession != null, "Client was not initialized successfully");
103         return Sets.newHashSet(clientSession.getServerCapabilities());
104     }
105
106     public static void main(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(String host, int port, boolean ssh, Optional<? extends
118             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.get());
128         } else {
129             b.withProtocol(NetconfClientProtocol.TCP);
130         }
131         return b.build();
132     }
133 }