Body implementation that keeps track of how many bytes are read.
| 24 | |
| 25 | /** {@link Body} implementation that keeps track of how many bytes are read. */ |
| 26 | public final class MeteredBody implements Body { |
| 27 | |
| 28 | private final Body delegate; |
| 29 | private Supplier<Long> count; |
| 30 | |
| 31 | public MeteredBody(Body body) { |
| 32 | this.delegate = body; |
| 33 | count = () -> 0L; |
| 34 | } |
| 35 | |
| 36 | @Override |
| 37 | public void close() throws IOException { |
| 38 | delegate.close(); |
| 39 | } |
| 40 | |
| 41 | @Override |
| 42 | public Integer length() { |
| 43 | return delegate.length(); |
| 44 | } |
| 45 | |
| 46 | @Override |
| 47 | public boolean isRepeatable() { |
| 48 | return delegate.isRepeatable(); |
| 49 | } |
| 50 | |
| 51 | @Override |
| 52 | public InputStream asInputStream() throws IOException { |
| 53 | // TODO, ideally, would like not to bring guava just for this |
| 54 | final CountingInputStream input = new CountingInputStream(delegate.asInputStream()); |
| 55 | count = input::getCount; |
| 56 | return input; |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public Reader asReader() throws IOException { |
| 61 | return new InputStreamReader(asInputStream(), UTF_8); |
| 62 | } |
| 63 | |
| 64 | public long count() { |
| 65 | return count.get(); |
| 66 | } |
| 67 | |
| 68 | @Override |
| 69 | public Reader asReader(Charset charset) throws IOException { |
| 70 | return new InputStreamReader(asInputStream(), charset); |
| 71 | } |
| 72 | } |
nothing calls this directly
no outgoing calls
no test coverage detected