BUG 624 - Make netconf TCP port optional.
[controller.git] / opendaylight / netconf / netconf-ssh / src / test / java / org / opendaylight / controller / netconf / netty / EchoServerHandler.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 com.google.common.base.Charsets;
12 import com.google.common.base.Splitter;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.channel.ChannelHandler.Sharable;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Handler implementation for the echo server.
22  */
23 @Sharable
24 public class EchoServerHandler extends ChannelInboundHandlerAdapter {
25
26     private static final Logger logger = LoggerFactory.getLogger(EchoServerHandler.class.getName());
27     private String fromLastNewLine = "";
28     private final Splitter splitter = Splitter.onPattern("\r?\n");
29     @Override
30     public void channelActive(ChannelHandlerContext ctx) throws Exception {
31         logger.debug("sleep start");
32         Thread.sleep(1000);
33         logger.debug("sleep done");
34     }
35
36     @Override
37     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
38         ByteBuf byteBuf = (ByteBuf) msg;
39         String message = byteBuf.toString(Charsets.UTF_8);
40         logger.info("writing back '{}'", message);
41         ctx.write(msg);
42         fromLastNewLine += message;
43         for (String line : splitter.split(fromLastNewLine)) {
44             if ("quit".equals(line)) {
45                 logger.info("closing server ctx");
46                 ctx.flush();
47                 ctx.close();
48                 break;
49             }
50             fromLastNewLine = line; // last line should be preserved
51         }
52
53         // do not release byteBuf as it is handled back
54     }
55
56     @Override
57     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
58         logger.debug("flushing");
59         ctx.flush();
60     }
61 }