]> gerrit.simantics Code Review - simantics/platform.git/blob - 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
1 package org.simantics.scl.rest;
2
3 import java.io.FilterOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.ext.WriterInterceptor;
9 import javax.ws.rs.ext.WriterInterceptorContext;
10
11 import org.simantics.scl.runtime.function.Function1;
12 import org.simantics.scl.runtime.tuple.Tuple0;
13
14 public class WriteProgressInterceptor implements WriterInterceptor {
15
16     private Function1<Long, Tuple0> callback;
17     
18     public WriteProgressInterceptor(Function1<Long, Tuple0> callback) {
19         this.callback = callback;
20     }
21
22     @Override
23     public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
24
25         final OutputStream os = context.getOutputStream();
26
27         context.setOutputStream(new FilterOutputStream(os) {
28             private long count;
29             
30             @Override public void write(byte[] b, int off, int len) throws IOException {
31                 out.write(b, off, len);
32                 count += len;
33                 callback.apply(count);
34             }
35
36             @Override
37             public void write(int b) throws IOException {
38                 out.write(b);
39                 count++;
40                 callback.apply(count);
41             }
42         });
43
44         context.proceed();
45     }
46
47 }