| 1 | package dolda.jsvc.scgi; |
| 2 | |
| 3 | import java.io.*; |
| 4 | |
| 5 | public class LimitInputStream extends InputStream { |
| 6 | private final InputStream bk; |
| 7 | private final long limit; |
| 8 | private long read; |
| 9 | |
| 10 | public LimitInputStream(InputStream bk, long limit) { |
| 11 | this.bk = bk; |
| 12 | this.limit = limit; |
| 13 | } |
| 14 | |
| 15 | public void close() throws IOException { |
| 16 | bk.close(); |
| 17 | } |
| 18 | |
| 19 | public int available() throws IOException { |
| 20 | int av = bk.available(); |
| 21 | synchronized(this) { |
| 22 | if(av > limit - read) |
| 23 | av = (int)(limit - read); |
| 24 | return(av); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | public int read() throws IOException { |
| 29 | synchronized(this) { |
| 30 | if(read >= limit) |
| 31 | return(-1); |
| 32 | int ret = bk.read(); |
| 33 | if(ret >= 0) |
| 34 | read++; |
| 35 | return(ret); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | public int read(byte[] b) throws IOException { |
| 40 | return(read(b, 0, b.length)); |
| 41 | } |
| 42 | |
| 43 | public int read(byte[] b, int off, int len) throws IOException { |
| 44 | synchronized(this) { |
| 45 | if(read >= limit) |
| 46 | return(-1); |
| 47 | if(len > limit - read) |
| 48 | len = (int)(limit - read); |
| 49 | int ret = bk.read(b, off, len); |
| 50 | if(ret > 0) |
| 51 | read += ret; |
| 52 | return(ret); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | public long skip(long n) throws IOException { |
| 57 | synchronized(this) { |
| 58 | if(n > limit - read) |
| 59 | n = limit - read; |
| 60 | long ret = bk.skip(n); |
| 61 | read += ret; |
| 62 | return(ret); |
| 63 | } |
| 64 | } |
| 65 | } |