]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/ReadProgressInterceptor.java
Improvements to SCL HTTP client
[simantics/platform.git] / bundles / org.simantics.scl.rest / src / org / simantics / scl / rest / ReadProgressInterceptor.java
1 package org.simantics.scl.rest;
2
3 import java.io.FilterInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6
7 import javax.ws.rs.WebApplicationException;
8 import javax.ws.rs.ext.ReaderInterceptor;
9 import javax.ws.rs.ext.ReaderInterceptorContext;
10
11 import org.simantics.scl.runtime.function.Function1;
12 import org.simantics.scl.runtime.tuple.Tuple0;
13
14 public class ReadProgressInterceptor implements ReaderInterceptor {
15
16     private Function1<Long, Tuple0> callback;
17     
18     public ReadProgressInterceptor(Function1<Long, Tuple0> callback) {
19         this.callback = callback;
20     }
21
22     @Override
23     public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
24
25         final InputStream is = context.getInputStream();
26         
27         context.setInputStream(new FilterInputStream(is) {
28             
29             private long count;
30             
31             @Override
32             public int read(byte b[], int off, int len) throws IOException {
33                 int read = in.read(b, off, len);
34                 if (read > 0) {
35                     count += read;
36                     callback.apply(count);
37                 }
38                 return read;
39             }
40             
41             @Override
42             public int read() throws IOException {
43                 int read = in.read();
44                 if (read > 0) {
45                     count++;
46                     callback.apply(count);
47                 }
48                 return read;
49             }
50         });
51         
52         return context.proceed();
53     }
54
55 }