]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/WriteProgressInterceptor.java
Improvements to SCL HTTP client
[simantics/platform.git] / bundles / org.simantics.scl.rest / src / org / simantics / scl / rest / WriteProgressInterceptor.java
diff --git a/bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/WriteProgressInterceptor.java b/bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/WriteProgressInterceptor.java
new file mode 100644 (file)
index 0000000..ebbc85f
--- /dev/null
@@ -0,0 +1,47 @@
+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<Long, Tuple0> callback;
+    
+    public WriteProgressInterceptor(Function1<Long, Tuple0> 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();
+    }
+
+}