1package tests.support;
2
3import java.io.IOException;
4import java.io.InputStream;
5
6/**
7 * An implementation of {@code InputStream} that should serve as the
8 * underlying stream for classes to be tested.
9 * In particular this implementation allows to have IOExecptions thrown on demand.
10 * For simplicity of use and understanding all fields are public.
11 */
12public class Support_ASimpleInputStream extends InputStream {
13
14    public static final int DEFAULT_BUFFER_SIZE = 32;
15
16    public byte[] buf;
17
18    public int pos;
19
20    public int len;
21
22    // Set to true when exception is wanted:
23    public boolean throwExceptionOnNextUse = false;
24
25    public Support_ASimpleInputStream() {
26        this("BEGIN Bla bla, some text...END");
27    }
28
29    public Support_ASimpleInputStream(boolean throwException) {
30        this();
31        throwExceptionOnNextUse = throwException;
32    }
33
34    public Support_ASimpleInputStream(String input) {
35        buf = input.getBytes();
36        pos = 0;
37        len = buf.length;
38    }
39
40    public Support_ASimpleInputStream(byte[] input) {
41        pos = 0;
42        len = input.length;
43        buf = new byte[len];
44        System.arraycopy(input, 0, buf, 0, len);
45    }
46
47    @Override
48    public void close() throws IOException {
49        if (throwExceptionOnNextUse) {
50            throw new IOException("Exception thrown for testing purpose.");
51        }
52    }
53
54    @Override
55    public int available() throws IOException {
56        if (throwExceptionOnNextUse) {
57            throw new IOException("Exception thrown for testing purpose.");
58        }
59        return len - pos;
60    }
61
62    @Override
63    public int read() throws IOException {
64        if (throwExceptionOnNextUse) {
65            throw new IOException("Exception thrown for testing purpose.");
66        }
67        if (pos < len) {
68            int res = buf[pos];
69            pos++;
70            return res;
71
72        } else {
73            return -1;
74        }
75    }
76}
77