d8dd7881653b466b24886da068f1d6bab529027b
[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.NetconfMessageConstants;
12 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
13
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.Unpooled;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.handler.codec.MessageToByteEncoder;
18
19 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
20
21     private NetconfMessageHeader messageHeader = new NetconfMessageHeader();
22
23     private final static int MAX_CHUNK_SIZE = NetconfMessageConstants.MAX_CHUNK_SIZE;
24
25     @Override
26     protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
27         while (msg.readableBytes() > MAX_CHUNK_SIZE) {
28             ByteBuf chunk = Unpooled.buffer(MAX_CHUNK_SIZE);
29             chunk.writeBytes(createChunkHeader(MAX_CHUNK_SIZE));
30             chunk.writeBytes(msg.readBytes(MAX_CHUNK_SIZE));
31             ctx.write(chunk);
32         }
33         out.writeBytes(createChunkHeader(msg.readableBytes()));
34         out.writeBytes(msg.readBytes(msg.readableBytes()));
35         out.writeBytes(NetconfMessageConstants.endOfChunk);
36     }
37
38     private ByteBuf createChunkHeader(int chunkSize) {
39         messageHeader.setLength(chunkSize);
40         return Unpooled.wrappedBuffer(messageHeader.toBytes());
41     }
42
43 }