2 * Copyright (c) 2015 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 java.io.IOException;
13 import java.io.Writer;
14 import javax.annotation.concurrent.NotThreadSafe;
17 * Custom BufferedWriter optimized for netconf pipeline implemented instead of default BufferedWriter provided by jdk.
20 * The line separator instance field in java.io.BufferedWriter is
21 * assigned using AccessController and takes considerable amount of time especially
22 * if lots of BufferedWriters are created in the system.
25 * This implementation should only be used if newLine method is not required
26 * such as netconf message to XML encoders.
27 * Methods in this implementation are not synchronized.
30 public final class BufferedWriter extends Writer {
32 private static final int DEFAULT_CHAR_BUFFER_SIZE = 8192;
34 private final Writer writer;
35 private final char[] buffer;
36 private final int bufferSize;
38 private int nextChar = 0;
40 public BufferedWriter(final Writer writer) {
41 this(writer, DEFAULT_CHAR_BUFFER_SIZE);
44 public BufferedWriter(final Writer writer, final int bufferSize) {
46 Preconditions.checkArgument(bufferSize > 0, "Buffer size <= 0");
48 this.buffer = new char[bufferSize];
49 this.bufferSize = bufferSize;
52 private void flushBuffer() throws IOException {
56 writer.write(buffer, 0, nextChar);
61 public void write(final int character) throws IOException {
62 if (nextChar >= bufferSize) {
65 buffer[nextChar++] = (char) character;
69 public void write(final char[] buffer, final int offset, final int length) throws IOException {
70 if ((offset < 0) || (offset > buffer.length)
71 || (length < 0) || ((offset + length) > buffer.length) || ((offset + length) < 0)) {
72 throw new IndexOutOfBoundsException(
73 String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length));
74 } else if (length == 0) {
78 if (length >= bufferSize) {
80 writer.write(buffer, offset, length);
84 int bufferOffset = offset;
85 final int t = offset + length;
86 while (bufferOffset < t) {
87 final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
88 System.arraycopy(buffer, bufferOffset, this.buffer, nextChar, d);
91 if (nextChar >= bufferSize) {
98 public void write(final String string, final int offset, final int length) throws IOException {
99 int bufferOffset = offset;
100 final int t = offset + length;
101 while (bufferOffset < t) {
102 final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
103 string.getChars(bufferOffset, bufferOffset + d, buffer, nextChar);
106 if (nextChar >= bufferSize) {
113 public void flush() throws IOException {
119 public void close() throws IOException {