package org.simantics.scl.rest; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; import org.simantics.scl.runtime.function.Function1; import org.simantics.scl.runtime.tuple.Tuple0; public class WriteProgressInterceptor implements WriterInterceptor { private Function1 callback; public WriteProgressInterceptor(Function1 callback) { this.callback = callback; } @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { final OutputStream os = context.getOutputStream(); context.setOutputStream(new FilterOutputStream(os) { private long count; @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); count += len; callback.apply(count); } @Override public void write(int b) throws IOException { out.write(b); count++; callback.apply(count); } }); context.proceed(); } }