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.Charsets;
12 import com.google.common.base.Preconditions;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.MessageToByteEncoder;
16 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
18 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
19 public static final int DEFAULT_CHUNK_SIZE = 8192;
20 public static final int MIN_CHUNK_SIZE = 128;
21 public static final int MAX_CHUNK_SIZE = 16 * 1024 * 1024;
23 private final int chunkSize;
25 public ChunkedFramingMechanismEncoder() {
26 this(DEFAULT_CHUNK_SIZE);
29 public ChunkedFramingMechanismEncoder(final int chunkSize) {
30 Preconditions.checkArgument(chunkSize >= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE, "Unsupported chunk size %s", chunkSize);
31 this.chunkSize = chunkSize;
34 public final int getChunkSize() {
39 protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out) {
41 final int xfer = Math.min(chunkSize, msg.readableBytes());
43 out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
44 out.writeBytes(String.valueOf(xfer).getBytes(Charsets.US_ASCII));
47 out.writeBytes(msg, xfer);
48 } while (msg.isReadable());
50 out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);