Bug 1029: Remove dead code: sal-schema-repository-api
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / 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.util.handler;
10
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.Unpooled;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.codec.MessageToByteEncoder;
15
16 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
17 import org.opendaylight.controller.netconf.util.messages.NetconfMessageHeader;
18
19 import com.google.common.base.Preconditions;
20
21 public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
22     public static final int DEFAULT_CHUNK_SIZE = 8192;
23     public static final int MIN_CHUNK_SIZE = 128;
24     public static final int MAX_CHUNK_SIZE = 16 * 1024 * 1024;
25
26     private final int chunkSize;
27
28     public ChunkedFramingMechanismEncoder() {
29         this(DEFAULT_CHUNK_SIZE);
30     }
31
32     public ChunkedFramingMechanismEncoder(int chunkSize) {
33         Preconditions.checkArgument(chunkSize > MIN_CHUNK_SIZE);
34         Preconditions.checkArgument(chunkSize < MAX_CHUNK_SIZE);
35         this.chunkSize = chunkSize;
36     }
37
38     public final int getChunkSize() {
39         return chunkSize;
40     }
41
42     @Override
43     protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out)  {
44         while (msg.readableBytes() > chunkSize) {
45             ByteBuf chunk = Unpooled.buffer(chunkSize);
46             chunk.writeBytes(createChunkHeader(chunkSize));
47             chunk.writeBytes(msg.readBytes(chunkSize));
48             ctx.write(chunk);
49         }
50         out.writeBytes(createChunkHeader(msg.readableBytes()));
51         out.writeBytes(msg.readBytes(msg.readableBytes()));
52         out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
53     }
54
55     private ByteBuf createChunkHeader(int chunkSize) {
56         return Unpooled.wrappedBuffer(NetconfMessageHeader.toBytes(chunkSize));
57     }
58 }