view src/cachingfilter/ProxyServletOutputStream.java @ 63:4987e1a38a6c

remove ads from homepage
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 28 Aug 2024 15:34:42 -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();
	}
}