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.netconf.nettyutil.handler;
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.codec.MessageToByteEncoder;
15 import java.nio.charset.StandardCharsets;
16 import org.opendaylight.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,
31 "Unsupported chunk size %s", chunkSize);
32 this.chunkSize = chunkSize;
35 public final int getChunkSize() {
40 protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out) {
42 final int xfer = Math.min(chunkSize, msg.readableBytes());
44 out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
45 out.writeBytes(String.valueOf(xfer).getBytes(StandardCharsets.US_ASCII));
48 out.writeBytes(msg, xfer);
49 } while (msg.isReadable());
51 out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);