Reworked Netconf framing mechanism, added chunked framing mechanism.
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfMessageChunkDecoder.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.nio.charset.Charset;
12 import java.util.List;
13
14 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
15 import org.opendaylight.protocol.framework.DeserializerException;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 import io.netty.buffer.ByteBuf;
20 import io.netty.buffer.Unpooled;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.ByteToMessageDecoder;
23
24 public class NetconfMessageChunkDecoder extends ByteToMessageDecoder {
25
26     private final static Logger logger = LoggerFactory.getLogger(NetconfMessageChunkDecoder.class);
27
28     @Override
29     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
30         ByteBuf byteBufMsg = Unpooled.buffer(in.readableBytes());
31         int chunkSize = -1;
32         boolean isParsed = false;
33         while (in.isReadable()) {
34             try {
35                 if (!isParsed) {
36                     chunkSize = readHeader(in);
37                     isParsed = true;
38                 }
39                 if (chunkSize != -1 && isParsed) {
40                     in.readBytes(byteBufMsg, chunkSize);
41                     logger.debug("Chunked data of size {} read.", chunkSize);
42                     isParsed = false;
43                 } else {
44                     throw new DeserializerException("Unable to parse chunked data or header.");
45                 }
46             } catch (Exception e) {
47                 logger.debug("Failed to decode chunked message.", e);
48                 this.exceptionCaught(ctx, e);
49             }
50         }
51         out.add(byteBufMsg);
52         isParsed = false;
53     }
54
55     private int readHeader(ByteBuf in) {
56         ByteBuf chunkSize = Unpooled.buffer(NetconfMessageHeader.MIN_HEADER_LENGTH,
57                 NetconfMessageHeader.MAX_HEADER_LENGTH);
58         byte b = in.readByte();
59         if (b != 10)
60             return -1;
61         b = in.readByte();
62         if (b != 35)
63             return -1;
64         while ((b = in.readByte()) != 10) {
65             chunkSize.writeByte(b);
66         }
67         return Integer.parseInt(chunkSize.toString(Charset.forName("UTF-8")));
68     }
69
70 }