Fix a few eclipse-reported warnings
[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.NetconfMessageConstants;
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                     isParsed = false;
42                 } else {
43                     throw new DeserializerException("Unable to parse chunked data or header.");
44                 }
45             } catch (Exception e) {
46                 logger.error("Failed to decode chunked message.", e);
47                 this.exceptionCaught(ctx, e);
48             }
49         }
50         out.add(byteBufMsg);
51         isParsed = false;
52     }
53
54     private int readHeader(ByteBuf in) {
55         ByteBuf chunkSize = Unpooled.buffer(NetconfMessageConstants.MIN_HEADER_LENGTH,
56                 NetconfMessageConstants.MAX_HEADER_LENGTH);
57         byte b = in.readByte();
58         if (b != 10)
59             return -1;
60         b = in.readByte();
61         if (b != 35)
62             return -1;
63         while ((b = in.readByte()) != 10) {
64             chunkSize.writeByte(b);
65         }
66         return Integer.parseInt(chunkSize.toString(Charset.forName("UTF-8")));
67     }
68
69 }