Speed up chunked framing
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / handler / ChunkedFramingMechanismEncoder.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.nettyutil.handler;
10
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;
17
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;
22
23     private final int chunkSize;
24
25     public ChunkedFramingMechanismEncoder() {
26         this(DEFAULT_CHUNK_SIZE);
27     }
28
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;
32     }
33
34     public final int getChunkSize() {
35         return chunkSize;
36     }
37
38     @Override
39     protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out)  {
40         do {
41             final int xfer = Math.min(chunkSize, msg.readableBytes());
42
43             out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
44             out.writeBytes(String.valueOf(xfer).getBytes(Charsets.US_ASCII));
45             out.writeByte('\n');
46
47             out.writeBytes(msg, xfer);
48         } while (msg.isReadable());
49
50         out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
51     }
52 }