view src/cachingfilter/ProxyServletOutputStream.java @ 4:e79c7d4dcd7a

fix email footer
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 25 Apr 2019 15:15:45 -0600
parents 7ecd1a4ef557
children
line wrap: on
line source

package cachingfilter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import javax.servlet.ServletOutputStream;


public abstract class ProxyServletOutputStream extends ServletOutputStream {
	private static final int BUFFER_SIZE = 100;

	private OutputStream out = new OutputStream() {
		private final ByteArrayOutputStream buf = new ByteArrayOutputStream();

		public void write(int b) throws IOException {
			buf.write(b);
			check();
		}
		
		public void write(byte b[]) throws IOException {
			buf.write(b);
			check();
		}
		
		public void write(byte b[], int off, int len) throws IOException {
			buf.write(b,off,len);
			check();
		}
		
		public void flush() throws IOException {
			setOut();
			out.flush();
		}
		
		public void close() throws IOException {
			setOut();
			out.close();
		}

		void check() throws IOException {
			if( buf.size() >= BUFFER_SIZE )
				setOut();
		}

		private void setOut() throws IOException {
			out = newOutputStream();
			out.write(buf.toByteArray());
		}
	};

	protected abstract OutputStream newOutputStream() throws IOException;
	
	public void write(int b) throws IOException {
		out.write(b);
	}
	
	public void write(byte b[]) throws IOException {
		out.write(b);
	}
	
	public void write(byte b[], int off, int len) throws IOException {
		out.write(b,off,len);
	}
	
	public void flush() throws IOException {
		out.flush();
	}
	
	public void close() throws IOException {
		out.close();
	}
}