+/**
+ * This {@link InputStream} can be separated into sub-streams (you can process
+ * it as a normal {@link InputStream} but, when it is spent, you can call
+ * {@link NextableInputStream#next()} on it to unlock new data).
+ * <p>
+ * The separation in sub-streams is done via {@link NextableInputStreamStep}.
+ *
+ * @author niki
+ */
+public class NextableInputStream extends BufferedInputStream {
+ private NextableInputStreamStep step;
+ private boolean started;
+ private boolean stopped;
+
+ /**
+ * Create a new {@link NextableInputStream} that wraps the given
+ * {@link InputStream}.
+ *
+ * @param in
+ * the {@link InputStream} to wrap
+ * @param step
+ * how to separate it into sub-streams (can be NULL, but in that
+ * case it will behave as a normal {@link InputStream})
+ */
+ public NextableInputStream(InputStream in, NextableInputStreamStep step) {
+ super(in);
+ this.step = step;
+ }
+
+ /**
+ * Create a new {@link NextableInputStream} that wraps the given bytes array
+ * as a data source.
+ *
+ * @param in
+ * the array to wrap, cannot be NULL
+ * @param step
+ * how to separate it into sub-streams (can be NULL, but in that
+ * case it will behave as a normal {@link InputStream})
+ */
+ public NextableInputStream(byte[] in, NextableInputStreamStep step) {
+ this(in, step, 0, in.length);
+ }
+
+ /**
+ * Create a new {@link NextableInputStream} that wraps the given bytes array
+ * as a data source.
+ *
+ * @param in
+ * the array to wrap, cannot be NULL
+ * @param step
+ * how to separate it into sub-streams (can be NULL, but in that
+ * case it will behave as a normal {@link InputStream})
+ * @param offset
+ * the offset to start the reading at
+ * @param length
+ * the number of bytes to take into account in the array,
+ * starting from the offset
+ *
+ * @throws NullPointerException
+ * if the array is NULL
+ * @throws IndexOutOfBoundsException
+ * if the offset and length do not correspond to the given array
+ */
+ public NextableInputStream(byte[] in, NextableInputStreamStep step,
+ int offset, int length) {
+ super(in, offset, length);
+ this.step = step;
+ checkBuffer(true);
+ }
+
+ /**
+ * Unblock the processing of the next sub-stream.
+ * <p>
+ * It can only be called when the "current" stream is spent (i.e., you must
+ * first process the stream until it is spent).
+ * <p>
+ * We consider that when the under-laying {@link InputStream} is also spent,
+ * we cannot have a next sub-stream (it will thus return FALSE).
+ * <p>
+ * {@link IOException}s can happen when we have no data available in the
+ * buffer; in that case, we fetch more data to know if we can have a next
+ * sub-stream or not.
+ *
+ * @return TRUE if we unblocked the next sub-stream, FALSE if not
+ *
+ * @throws IOException
+ * in case of I/O error or if the stream is closed
+ */
+ public boolean next() throws IOException {
+ return next(false);