summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java
blob: 77359817519cce70fbf24aad175127b82df6fa83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package bjc.utils.ioutils.blocks;

import java.io.IOException;
import java.util.Deque;

/**
 * Provides a means of concatenating two block readers.
 *
 * @author bjculkin
 *
 */
public class SerialBlockReader implements BlockReader {
	private Deque<BlockReader> readerQueue;

	private int blockNo;

	/**
	 * Create a new serial block reader.
	 *
	 * @param readers
	 *                The readers to pull from, in the order to pull from
	 *                them.
	 */
	public SerialBlockReader(final BlockReader... readers) {
		for (final BlockReader reader : readers) {
			readerQueue.add(reader);
		}
	}

	@Override
	public boolean hasNextBlock() {
		if (readerQueue.isEmpty()) return false;

		boolean hasBlock = readerQueue.peek().hasNextBlock();

		boolean cont = hasBlock || readerQueue.isEmpty();

		while (!cont) {
			try {
				readerQueue.pop().close();
			} catch (final IOException ioex) {
				throw new IllegalStateException("Exception thrown by discarded reader", ioex);
			}

			hasBlock = readerQueue.peek().hasNextBlock();

			cont = hasBlock || readerQueue.isEmpty();
		}

		return hasBlock;
	}

	@Override
	public Block getBlock() {
		if (readerQueue.isEmpty())
			return null;
		else return readerQueue.peek().getBlock();
	}

	@Override
	public boolean nextBlock() {
		if (readerQueue.isEmpty()) return false;

		boolean gotBlock = readerQueue.peek().nextBlock();

		boolean cont = gotBlock || readerQueue.isEmpty();

		while (!cont) {
			try {
				readerQueue.pop().close();
			} catch (final IOException ioex) {
				throw new IllegalStateException("Exception thrown by discarded reader", ioex);
			}

			gotBlock = readerQueue.peek().nextBlock();

			cont = gotBlock || readerQueue.isEmpty();
		}

		if (cont) {
			blockNo += 1;
		}

		return cont;
	}

	@Override
	public int getBlockCount() {
		return blockNo;
	}

	@Override
	public void close() throws IOException {
		while (!readerQueue.isEmpty()) {
			final BlockReader reader = readerQueue.pop();

			reader.close();
		}
	}
}