001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019
020 package org.apache.myfaces.tobago.util;
021
022 import org.apache.commons.logging.Log;
023 import org.apache.commons.logging.LogFactory;
024
025 import java.io.IOException;
026 import java.io.Writer;
027
028 //
029 // Buffering scheme: we use a tremendously simple buffering
030 // scheme that greatly reduces the number of calls into the
031 // Writer/PrintWriter. In practice this has produced significant
032 // measured performance gains (at least in JDK 1.3.1). We only
033 // support adding single characters to the buffer, so anytime
034 // multiple characters need to be written out, the entire buffer
035 // gets flushed. In practice, this is good enough, and keeps
036 // the core simple.
037 //
038
039 /**
040 * User: lofwyr
041 * Date: 07.05.2007 12:03:26
042 */
043 public class ResponseWriterBuffer {
044
045 private static final Log LOG = LogFactory.getLog(ResponseWriterBuffer.class);
046
047 private static final int BUFFER_SIZE = 64;
048
049 private final char[] buff = new char[BUFFER_SIZE];
050
051 private int bufferIndex;
052
053 private final Writer writer;
054
055 public ResponseWriterBuffer(final Writer writer) {
056 this.writer = writer;
057 }
058
059 /**
060 * Add a character to the buffer, flushing the buffer if the buffer is
061 * full
062 */
063 public void addToBuffer(final char ch) throws IOException {
064 if (bufferIndex >= BUFFER_SIZE) {
065 writer.write(buff, 0, bufferIndex);
066 bufferIndex = 0;
067 }
068
069 buff[bufferIndex++] = ch;
070 }
071
072 public void addToBuffer(final char[] ch) throws IOException {
073 if (bufferIndex + ch.length >= BUFFER_SIZE) {
074 writer.write(buff, 0, bufferIndex);
075 bufferIndex = 0;
076 }
077
078 System.arraycopy(ch, 0, buff, bufferIndex, ch.length);
079 bufferIndex += ch.length;
080 }
081
082 /**
083 * Flush the contents of the buffer to the output stream
084 * and return the reset buffer index
085 */
086 public void flushBuffer() throws IOException {
087 if (bufferIndex > 0) {
088 writer.write(buff, 0, bufferIndex);
089 }
090 bufferIndex = 0;
091 }
092 }