2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.util.handler;
11 import java.nio.charset.Charset;
12 import java.util.List;
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;
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;
24 public class NetconfMessageChunkDecoder extends ByteToMessageDecoder {
26 private final static Logger logger = LoggerFactory.getLogger(NetconfMessageChunkDecoder.class);
29 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
30 ByteBuf byteBufMsg = Unpooled.buffer(in.readableBytes());
32 boolean isParsed = false;
33 while (in.isReadable()) {
36 chunkSize = readHeader(in);
39 if (chunkSize != -1 && isParsed) {
40 in.readBytes(byteBufMsg, chunkSize);
43 throw new DeserializerException("Unable to parse chunked data or header.");
45 } catch (Exception e) {
46 logger.error("Failed to decode chunked message.", e);
47 this.exceptionCaught(ctx, e);
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();
63 while ((b = in.readByte()) != 10) {
64 chunkSize.writeByte(b);
66 return Integer.parseInt(chunkSize.toString(Charset.forName("UTF-8")));