Merge "BUG-625: migrate InventoryAndReadAdapter"
[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 implements Runnable {
29     private static final Logger logger = LoggerFactory.getLogger(EchoClient.class);
30
31     private final ChannelHandler clientHandler;
32
33
34     public EchoClient(ChannelHandler clientHandler) {
35         this.clientHandler = clientHandler;
36     }
37
38     public void run() {
39         // Configure the client.
40         EventLoopGroup group = new NioEventLoopGroup();
41         try {
42             Bootstrap b = new Bootstrap();
43             b.group(group)
44                     .channel(LocalChannel.class)
45                     .handler(new ChannelInitializer<LocalChannel>() {
46                         @Override
47                         public void initChannel(LocalChannel ch) throws Exception {
48                             ch.pipeline().addLast(clientHandler);
49                         }
50                     });
51
52             // Start the client.
53             LocalAddress localAddress = new LocalAddress("foo");
54             ChannelFuture f = b.connect(localAddress).sync();
55
56             // Wait until the connection is closed.
57             f.channel().closeFuture().sync();
58         } catch (Exception e) {
59             logger.error("Error in client", e);
60             throw new RuntimeException("Error in client", e);
61         } finally {
62             // Shut down the event loop to terminate all threads.
63             logger.info("Client is shutting down");
64             group.shutdownGracefully();
65         }
66     }
67 }