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 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;
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;
24 private final int chunkSize;
26 public ChunkedFramingMechanismEncoder() {
27 this(DEFAULT_CHUNK_SIZE);
30 public ChunkedFramingMechanismEncoder(int chunkSize) {
31 Preconditions.checkArgument(chunkSize > MIN_CHUNK_SIZE);
32 Preconditions.checkArgument(chunkSize < MAX_CHUNK_SIZE);
33 this.chunkSize = chunkSize;
36 public final int getChunkSize() {
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));
48 out.writeBytes(createChunkHeader(msg.readableBytes()));
49 out.writeBytes(msg.readBytes(msg.readableBytes()));
50 out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
53 private ByteBuf createChunkHeader(int chunkSize) {
54 return Unpooled.wrappedBuffer(NetconfMessageHeader.toBytes(chunkSize));