view src/cachingfilter/ProxyServletOutputStream.java @ 3:1010f557927f

allow setting salt for backup file
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 25 Mar 2019 18:38:18 -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();
	}
}