Merge "Remove netconf-impl's getConfig_candidate.xml"
[netconf.git] / netconf / mdsal-netconf-ssh / src / test / java / org / opendaylight / 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.netconf.netty;
10
11 import com.google.common.base.Splitter;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.channel.ChannelHandler.Sharable;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.ChannelInboundHandlerAdapter;
16 import java.nio.charset.StandardCharsets;
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 LOG = LoggerFactory.getLogger(EchoServerHandler.class);
27     private String fromLastNewLine = "";
28     private final Splitter splitter = Splitter.onPattern("\r?\n");
29
30     @Override
31     public void channelActive(ChannelHandlerContext ctx) throws Exception {
32         LOG.debug("sleep start");
33         Thread.sleep(1000);
34         LOG.debug("sleep done");
35     }
36
37     @Override
38     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
39         ByteBuf byteBuf = (ByteBuf) msg;
40         String message = byteBuf.toString(StandardCharsets.UTF_8);
41         LOG.info("writing back '{}'", message);
42         ctx.write(msg);
43         fromLastNewLine += message;
44         for (String line : splitter.split(fromLastNewLine)) {
45             if ("quit".equals(line)) {
46                 LOG.info("closing server ctx");
47                 ctx.flush();
48                 ctx.close();
49                 break;
50             }
51             fromLastNewLine = line; // last line should be preserved
52         }
53
54         // do not release byteBuf as it is handled back
55     }
56
57     @Override
58     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
59         LOG.debug("flushing");
60         ctx.flush();
61     }
62 }