Merge "Netconf-cli compilable and included in project"
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / 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.nettyutil.handler;
10
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.Unpooled;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.MessageToByteEncoder;
16 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
17 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
18
19 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
20     public static final int DEFAULT_CHUNK_SIZE = 8192;
21     public static final int MIN_CHUNK_SIZE = 128;
22     public static final int MAX_CHUNK_SIZE = 16 * 1024 * 1024;
23
24     private final int chunkSize;
25
26     public ChunkedFramingMechanismEncoder() {
27         this(DEFAULT_CHUNK_SIZE);
28     }
29
30     public ChunkedFramingMechanismEncoder(int chunkSize) {
31         Preconditions.checkArgument(chunkSize > MIN_CHUNK_SIZE);
32         Preconditions.checkArgument(chunkSize < MAX_CHUNK_SIZE);
33         this.chunkSize = chunkSize;
34     }
35
36     public final int getChunkSize() {
37         return chunkSize;
38     }
39
40     @Override
41     protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out)  {
42         while (msg.readableBytes() > chunkSize) {
43             ByteBuf chunk = Unpooled.buffer(chunkSize);
44             chunk.writeBytes(createChunkHeader(chunkSize));
45             chunk.writeBytes(msg.readBytes(chunkSize));
46             ctx.write(chunk);
47         }
48         out.writeBytes(createChunkHeader(msg.readableBytes()));
49         out.writeBytes(msg.readBytes(msg.readableBytes()));
50         out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
51     }
52
53     private ByteBuf createChunkHeader(int chunkSize) {
54         return Unpooled.wrappedBuffer(NetconfMessageHeader.toBytes(chunkSize));
55     }
56 }