View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.internal.util;
21  
22  import java.io.IOException;
23  import java.io.Writer;
24  
25  /**
26   * Buffering scheme: we use a tremendously simple buffering
27   * scheme that greatly reduces the number of calls into the
28   * Writer/PrintWriter.  In practice this has produced significant
29   * measured performance gains (at least in JDK 1.3.1).  We only
30   * support adding single characters to the buffer, so anytime
31   * multiple characters need to be written out, the entire buffer
32   * gets flushed.  In practice, this is good enough, and keeps
33   * the core simple.
34   */
35  public class ResponseWriterBuffer {
36  
37    private static final int BUFFER_SIZE = 64;
38  
39    private final char[] buff = new char[BUFFER_SIZE];
40  
41    private int bufferIndex;
42  
43    private final Writer writer;
44  
45    public ResponseWriterBuffer(final Writer writer) {
46      this.writer = writer;
47    }
48  
49    /**
50     * Add a character to the buffer, flushing the buffer if the buffer is
51     * full, and returning the new buffer index
52     */
53    public void addToBuffer(final char ch) throws IOException {
54      if (bufferIndex >= BUFFER_SIZE) {
55        writer.write(buff, 0, bufferIndex);
56        bufferIndex = 0;
57      }
58  
59      buff[bufferIndex++] = ch;
60    }
61  
62    public void addToBuffer(final char[] ch) throws IOException {
63      if (bufferIndex + ch.length >= BUFFER_SIZE) {
64        writer.write(buff, 0, bufferIndex);
65        bufferIndex = 0;
66      }
67  
68      System.arraycopy(ch, 0, buff, bufferIndex, ch.length);
69      bufferIndex += ch.length;
70    }
71  
72    /**
73     * Flush the contents of the buffer to the output stream
74     * and return the reset buffer index
75     */
76    public void flushBuffer() throws IOException {
77      if (bufferIndex > 0) {
78        writer.write(buff, 0, bufferIndex);
79      }
80      bufferIndex = 0;
81    }
82  }