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