1 /* 2 * Copyright 2009-2012 Capgemini and others 3 * 4 * Licensed under the Apache License, Version 2.0 5 * (the "License"); you may not use this file except in compliance with the 6 * License. You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 package net.sourceforge.statelessfilter.wrappers; 17 18 import java.io.ByteArrayOutputStream; 19 20 import javax.servlet.ServletOutputStream; 21 22 import net.sourceforge.statelessfilter.wrappers.headers.HeaderBufferedHttpResponseWrapper; 23 24 /** 25 * A custom servlet output stream that stores its data in a buffer, rather than 26 * sending it directly to the client. 27 * 28 * <p> 29 * In most cases, it is better to use {@link HeaderBufferedHttpResponseWrapper} instead. 30 * 31 * 32 * @author Eric M. Burke 33 * @author Nicolas Richeton 34 */ 35 public class BufferedServletOutputStream extends ServletOutputStream { 36 // the actual buffer 37 private ByteArrayOutputStream bos = new ByteArrayOutputStream(); 38 private boolean hasData = false; 39 40 /** 41 * @return the contents of the buffer. 42 */ 43 public byte[] getBuffer() { 44 return this.bos.toByteArray(); 45 } 46 47 // BufferedHttpResponseWrapper calls this method 48 public void reset() { 49 this.bos.reset(); 50 } 51 52 // BufferedHttpResponseWrapper calls this method 53 public void setBufferSize(int size) { 54 // no way to resize an existing ByteArrayOutputStream 55 // this.bos = new ByteArrayOutputStream(size); 56 } 57 58 /** 59 * This method must be defined for custom servlet output streams. 60 */ 61 @Override 62 public void write(int data) { 63 if (!hasData) 64 hasData = true; 65 this.bos.write(data); 66 67 } 68 69 public boolean hasData() { 70 71 return hasData; 72 } 73 }