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