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
8 package org.opendaylight.netconf.nettyutil.handler;
10 import com.google.common.base.Preconditions;
11 import java.io.IOException;
12 import java.io.Writer;
15 * Custom BufferedWriter optimized for netconf pipeline implemented instead of default BufferedWriter provided by jdk.
18 * The line separator instance field in java.io.BufferedWriter is
19 * assigned using AccessController and takes considerable amount of time especially
20 * if lots of BufferedWriters are created in the system.
23 * This implementation should only be used if newLine method is not required
24 * such as netconf message to XML encoders.
25 * Methods in this implementation are not synchronized.
27 public final class BufferedWriter extends Writer {
29 private static final int DEFAULT_CHAR_BUFFER_SIZE = 8192;
31 private final Writer writer;
32 private final char[] buffer;
33 private final int bufferSize;
35 private int nextChar = 0;
37 public BufferedWriter(final Writer writer) {
38 this(writer, DEFAULT_CHAR_BUFFER_SIZE);
41 public BufferedWriter(final Writer writer, final int bufferSize) {
43 Preconditions.checkArgument(bufferSize > 0, "Buffer size <= 0");
45 this.buffer = new char[bufferSize];
46 this.bufferSize = bufferSize;
49 private void flushBuffer() throws IOException {
53 writer.write(buffer, 0, nextChar);
58 public void write(final int character) throws IOException {
59 if (nextChar >= bufferSize) {
62 buffer[nextChar++] = (char) character;
66 @SuppressWarnings("checkstyle:hiddenField")
67 public void write(final char[] buffer, final int offset, final int length) throws IOException {
68 if (offset < 0 || offset > buffer.length
69 || length < 0 || offset + length > buffer.length || offset + length < 0) {
70 throw new IndexOutOfBoundsException(
71 String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length));
72 } else if (length == 0) {
76 if (length >= bufferSize) {
78 writer.write(buffer, offset, length);
82 int bufferOffset = offset;
83 final int t = offset + length;
84 while (bufferOffset < t) {
85 final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
86 System.arraycopy(buffer, bufferOffset, this.buffer, nextChar, d);
89 if (nextChar >= bufferSize) {
96 public void write(final String string, final int offset, final int length) throws IOException {
97 int bufferOffset = offset;
98 final int t = offset + length;
99 while (bufferOffset < t) {
100 final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
101 string.getChars(bufferOffset, bufferOffset + d, buffer, nextChar);
104 if (nextChar >= bufferSize) {
111 public void flush() throws IOException {
117 public void close() throws IOException {