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.nettyutil.handler;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.Unpooled;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.codec.MessageToByteEncoder;
16 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
17 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
19 import com.google.common.base.Preconditions;
21 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
22 public static final int DEFAULT_CHUNK_SIZE = 8192;
23 public static final int MIN_CHUNK_SIZE = 128;
24 public static final int MAX_CHUNK_SIZE = 16 * 1024 * 1024;
26 private final int chunkSize;
28 public ChunkedFramingMechanismEncoder() {
29 this(DEFAULT_CHUNK_SIZE);
32 public ChunkedFramingMechanismEncoder(int chunkSize) {
33 Preconditions.checkArgument(chunkSize > MIN_CHUNK_SIZE);
34 Preconditions.checkArgument(chunkSize < MAX_CHUNK_SIZE);
35 this.chunkSize = chunkSize;
38 public final int getChunkSize() {
43 protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
44 while (msg.readableBytes() > chunkSize) {
45 ByteBuf chunk = Unpooled.buffer(chunkSize);
46 chunk.writeBytes(createChunkHeader(chunkSize));
47 chunk.writeBytes(msg.readBytes(chunkSize));
50 out.writeBytes(createChunkHeader(msg.readableBytes()));
51 out.writeBytes(msg.readBytes(msg.readableBytes()));
52 out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
55 private ByteBuf createChunkHeader(int chunkSize) {
56 return Unpooled.wrappedBuffer(NetconfMessageHeader.toBytes(chunkSize));