001package media;
002
003import java.io.FilterInputStream;
004import java.io.IOException;
005import java.io.InputStream;
006
007/**
008 * <p>Stream che permette la lettura di byte fino a un limite arbitrario.</p>
009 * <p>Se il limite fissato viene superato, un ulteriore tentativo di lettura provoca il lancio di una {@link ReadLimitExceededException}</p>
010 */
011public class LimitedInputStream extends FilterInputStream {
012    private final long byteLimit;
013    private long byteRead = 0;
014
015
016    public LimitedInputStream(InputStream in, long byteLimit){
017        super(in);
018        this.byteLimit = byteLimit;
019    }
020
021    @Override
022    public int read() throws IOException {
023        int bite = super.read();
024        this.byteRead++;
025        if(this.byteRead > byteLimit)
026            throw new ReadLimitExceededException();
027        return bite;
028    }
029
030    @Override
031    public int read(byte[] b) throws IOException {
032        return super.read(b);
033    }
034
035    @Override
036    public int read(byte[] b, int off, int len) throws IOException {
037        int byteRead = super.read(b,off,len);
038        this.byteRead += byteRead;
039        if(this.byteRead > byteLimit)
040            throw new ReadLimitExceededException();
041        return byteRead;
042    }
043}