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
8 package org.opendaylight.netconf.nettyutil.handler;
10 import io.netty.buffer.ByteBuf;
11 import io.netty.channel.ChannelHandlerContext;
12 import java.nio.charset.StandardCharsets;
13 import org.opendaylight.netconf.api.messages.FramingMechanism;
16 * A {@link FramingMechanismEncoder} handling {@link FramingMechanism#CHUNK}.
18 public final class ChunkedFramingMechanismEncoder extends FramingMechanismEncoder {
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 if (chunkSize < MIN_CHUNK_SIZE) {
31 throw new IllegalArgumentException(chunkSize + " is lower than minimum supported " + MIN_CHUNK_SIZE);
33 if (chunkSize > MAX_CHUNK_SIZE) {
34 throw new IllegalArgumentException(chunkSize + " is lower than maximum supported " + MAX_CHUNK_SIZE);
36 this.chunkSize = chunkSize;
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(MessageParts.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(MessageParts.END_OF_CHUNK);