Refactor FramingMechanismHandlerFactory
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / 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 package org.opendaylight.netconf.nettyutil.handler;
9
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;
14
15 /**
16  * A {@link FramingMechanismEncoder} handling {@link FramingMechanism#CHUNK}.
17  */
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;
22
23     private final int chunkSize;
24
25     public ChunkedFramingMechanismEncoder() {
26         this(DEFAULT_CHUNK_SIZE);
27     }
28
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);
32         }
33         if (chunkSize > MAX_CHUNK_SIZE) {
34             throw new IllegalArgumentException(chunkSize + " is lower than maximum supported " + MAX_CHUNK_SIZE);
35         }
36         this.chunkSize = chunkSize;
37     }
38
39     @Override
40     protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out)  {
41         do {
42             final int xfer = Math.min(chunkSize, msg.readableBytes());
43
44             out.writeBytes(MessageParts.START_OF_CHUNK);
45             out.writeBytes(String.valueOf(xfer).getBytes(StandardCharsets.US_ASCII));
46             out.writeByte('\n');
47
48             out.writeBytes(msg, xfer);
49         } while (msg.isReadable());
50
51         out.writeBytes(MessageParts.END_OF_CHUNK);
52     }
53 }