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.controller.netconf.nettyutil.handler;
12 import com.google.common.base.Preconditions;
13 import java.io.IOException;
14 import java.io.Writer;
15 import javax.annotation.concurrent.NotThreadSafe;
18 * 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.
24 * This implementation should only be used if newLine method is not required
25 * such as netconf message to XML encoders.
26 * Methods in this implementation are not synchronized.
29 public final class BufferedWriter extends Writer {
31 private static final int DEFAULT_CHAR_BUFFER_SIZE = 8192;
33 private final Writer writer;
34 private final char buffer[];
35 private final int bufferSize;
37 private int nextChar = 0;
39 public BufferedWriter(final Writer writer) {
40 this(writer, DEFAULT_CHAR_BUFFER_SIZE);
43 public BufferedWriter(final Writer writer, final int bufferSize) {
45 Preconditions.checkArgument(bufferSize > 0, "Buffer size <= 0");
47 this.buffer = new char[bufferSize];
48 this.bufferSize = bufferSize;
51 private void flushBuffer() throws IOException {
54 writer.write(buffer, 0, nextChar);
59 public void write(final int c) throws IOException {
60 if (nextChar >= bufferSize)
62 buffer[nextChar++] = (char) c;
66 public void write(final char[] buffer, final int offset, final int length) throws IOException {
67 if ((offset < 0) || (offset > buffer.length) || (length < 0) ||
68 ((offset + length) > buffer.length) || ((offset + length) < 0)) {
69 throw new IndexOutOfBoundsException(String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length));
70 } else if (length == 0) {
74 if (length >= bufferSize) {
76 writer.write(buffer, offset, length);
81 final int t = offset + length;
83 final int d = Math.min(bufferSize - nextChar, t - b);
84 System.arraycopy(buffer, b, this.buffer, nextChar, d);
87 if (nextChar >= bufferSize)
93 public void write(final String string, final int offset, final int length) throws IOException {
95 final int t = offset + length;
97 final int d = Math.min(bufferSize - nextChar, t - b);
98 string.getChars(b, b + d, buffer, nextChar);
101 if (nextChar >= bufferSize)
107 public void flush() throws IOException {
113 public void close() throws IOException {