Convert mdsal-netconf-ssh to OSGi DS
[netconf.git] / netconf / mdsal-netconf-ssh / src / test / java / org / opendaylight / netconf / ssh / EchoClient.java
1 /*
2  * Copyright (c) 2014 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.ssh;
9
10 import io.netty.bootstrap.Bootstrap;
11 import io.netty.channel.ChannelFuture;
12 import io.netty.channel.ChannelHandler;
13 import io.netty.channel.ChannelInitializer;
14 import io.netty.channel.EventLoopGroup;
15 import io.netty.channel.local.LocalAddress;
16 import io.netty.channel.local.LocalChannel;
17 import io.netty.channel.nio.NioEventLoopGroup;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Sends one message when a connection is open and echoes back any received
23  * data to the server.  Simply put, the echo client initiates the ping-pong
24  * traffic between the echo client and server by sending the first message to
25  * the server.
26  */
27 public class EchoClient extends Thread {
28     private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
29
30     private final ChannelInitializer<LocalChannel> channelInitializer;
31
32     public EchoClient(final ChannelHandler clientHandler) {
33         channelInitializer = new ChannelInitializer<>() {
34             @Override
35             public void initChannel(final LocalChannel ch) {
36                 ch.pipeline().addLast(clientHandler);
37             }
38         };
39     }
40
41     public EchoClient(final ChannelInitializer<LocalChannel> channelInitializer) {
42         this.channelInitializer = channelInitializer;
43     }
44
45     @Override
46     public void run() {
47         // Configure the client.
48         EventLoopGroup group = new NioEventLoopGroup();
49         try {
50             Bootstrap bootstrap = new Bootstrap();
51
52             bootstrap.group(group)
53                     .channel(LocalChannel.class)
54                     .handler(channelInitializer);
55
56             // Start the client.
57             LocalAddress localAddress = new LocalAddress("foo");
58             ChannelFuture future = bootstrap.connect(localAddress).sync();
59
60             // Wait until the connection is closed.
61             future.channel().closeFuture().sync();
62         } catch (InterruptedException e) {
63             LOG.error("Error in client", e);
64             throw new RuntimeException("Error in client", e);
65         } finally {
66             // Shut down the event loop to terminate all threads.
67             LOG.info("Client is shutting down");
68             group.shutdownGracefully();
69         }
70     }
71 }