868ddbd99c37a07a6fd31198cd81fe01c654e662
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfMessageAggregator.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 java.util.List;
12
13 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
14 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.handler.codec.ByteToMessageDecoder;
21
22 public class NetconfMessageAggregator extends ByteToMessageDecoder {
23
24     private final static Logger logger = LoggerFactory.getLogger(NetconfMessageAggregator.class);
25
26     private byte[] eom = NetconfMessageConstants.endOfMessage;
27
28     public NetconfMessageAggregator(FramingMechanism framingMechanism) {
29         if (framingMechanism == FramingMechanism.CHUNK) {
30             eom = NetconfMessageConstants.endOfChunk;
31         }
32     }
33
34     @Override
35     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
36         int index = indexOfSequence(in, eom);
37         if (index == -1) {
38             logger.debug("Message is not complete, read agian.");
39             ctx.read();
40         } else {
41             ByteBuf msg = in.readBytes(index);
42             in.readBytes(eom.length);
43             in.discardReadBytes();
44             logger.debug("Message is complete.");
45             out.add(msg);
46         }
47     }
48
49     private int indexOfSequence(ByteBuf in, byte[] sequence) {
50         int index = -1;
51         for (int i = 0; i < in.readableBytes() - sequence.length + 1; i++) {
52             if (in.getByte(i) == sequence[0]) {
53                 index = i;
54                 for (int j = 1; j < sequence.length; j++) {
55                     if (in.getByte(i + j) != sequence[j]) {
56                         index = -1;
57                         break;
58                     }
59                 }
60                 if (index != -1) {
61                     return index;
62                 }
63             }
64         }
65         return index;
66     }
67
68 }