Merge "Bug 809: Enhancements to the toaster example"
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfEOMAggregator.java
1 /*
2  * Copyright (c) 2013 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.util.handler;
10
11 import io.netty.buffer.ByteBuf;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14
15 import java.util.List;
16
17 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import com.google.common.base.Charsets;
22
23 public class NetconfEOMAggregator extends ByteToMessageDecoder {
24     private final static Logger logger = LoggerFactory.getLogger(NetconfEOMAggregator.class);
25
26     @Override
27     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
28         int index = indexOfSequence(in, NetconfMessageConstants.END_OF_MESSAGE);
29         if (index == -1) {
30             logger.debug("Message is not complete, read again.");
31             if (logger.isTraceEnabled()) {
32                 String str = in.toString(Charsets.UTF_8);
33                 logger.trace("Message read so far: {}", str);
34             }
35             ctx.read();
36         } else {
37             ByteBuf msg = in.readBytes(index);
38             in.readBytes(NetconfMessageConstants.END_OF_MESSAGE.length);
39             in.discardReadBytes();
40             logger.debug("Message is complete.");
41             out.add(msg);
42         }
43     }
44
45     private int indexOfSequence(ByteBuf in, byte[] sequence) {
46         int index = -1;
47         for (int i = 0; i < in.readableBytes() - sequence.length + 1; i++) {
48             if (in.getByte(i) == sequence[0]) {
49                 index = i;
50                 for (int j = 1; j < sequence.length; j++) {
51                     if (in.getByte(i + j) != sequence[j]) {
52                         index = -1;
53                         break;
54                     }
55                 }
56                 if (index != -1) {
57                     return index;
58                 }
59             }
60         }
61         return index;
62     }
63
64 }