Merge "Bug 1073: Added Transaction Chain support to InMemoryDataTreeModification."
[controller.git] / opendaylight / netconf / netconf-ssh / src / test / java / org / opendaylight / controller / netconf / netty / EchoClientHandler.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 static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.base.Charsets;
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.Unpooled;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Handler implementation for the echo client.  It initiates the ping-pong
23  * traffic between the echo client and server by sending the first message to
24  * the server.
25  */
26 public class EchoClientHandler extends ChannelInboundHandlerAdapter {
27     private static final Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);
28
29     private ChannelHandlerContext ctx;
30
31     @Override
32     public void channelActive(ChannelHandlerContext ctx) {
33         checkState(this.ctx == null);
34         logger.info("client active");
35         this.ctx = ctx;
36     }
37
38     @Override
39     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
40         ByteBuf bb = (ByteBuf) msg;
41         logger.info(">{}", bb.toString(Charsets.UTF_8));
42         bb.release();
43     }
44
45     @Override
46     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
47     }
48
49     @Override
50     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
51         // Close the connection when an exception is raised.
52         logger.warn("Unexpected exception from downstream.", cause);
53         checkState(this.ctx.equals(ctx));
54         ctx.close();
55         this.ctx = null;
56     }
57
58     public void write(String message) {
59         ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes());
60         ctx.writeAndFlush(byteBuf);
61     }
62 }