Reworked Netconf framing mechanism, added chunked framing mechanism.
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / ChunkedFramingMechanismEncoder.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 org.opendaylight.controller.netconf.util.messages.NetconfMessageFactory;
12 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.Unpooled;
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.handler.codec.MessageToByteEncoder;
20
21 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
22
23     private final static Logger logger = LoggerFactory.getLogger(ChunkedFramingMechanismEncoder.class);
24
25     private NetconfMessageHeader messageHeader = new NetconfMessageHeader();
26
27     @Override
28     protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
29         while (msg.readableBytes() > NetconfMessageFactory.MAX_CHUNK_SIZE) {
30             ByteBuf chunk = Unpooled.buffer(NetconfMessageFactory.MAX_CHUNK_SIZE);
31             chunk.writeBytes(createChunkHeader(NetconfMessageFactory.MAX_CHUNK_SIZE));
32             chunk.writeBytes(msg.readBytes(NetconfMessageFactory.MAX_CHUNK_SIZE));
33             ctx.write(chunk);
34         }
35         out.writeBytes(createChunkHeader(msg.readableBytes()));
36         out.writeBytes(msg.readBytes(msg.readableBytes()));
37         out.writeBytes(NetconfMessageFactory.endOfChunk);
38         logger.debug("Output message size is {}", out.readableBytes());
39     }
40
41     private ByteBuf createChunkHeader(int chunkSize) {
42         messageHeader.setLength(chunkSize);
43         logger.debug("Chunked data length is {}.", chunkSize);
44         return Unpooled.wrappedBuffer(messageHeader.toBytes());
45     }
46
47 }