* An object to iterate over protobuf messages in a file.
* A ReportStream is opened upon creation and is closed by invoking the close method.
*
- * Warning, while it extends Iterable, it is not a general-purpose Iterable as it supports only a single Iterator;
- * invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.
- *
* Inspired by {@link java.nio.file.DirectoryStream}
*/
public class ReportStream<R extends Message> implements Closeable, Iterable<R> {
+ private final File file;
private final Parser<R> parser;
private InputStream inputStream;
- private ReportIterator<R> iterator;
public ReportStream(File file, Parser<R> parser) {
+ this.file = file;
this.parser = parser;
- this.inputStream = ProtobufUtil.createInputStream(file);
}
@Override
public Iterator<R> iterator() {
- if (this.iterator != null) {
- throw new IllegalStateException("Iterator already obtained");
- } else {
- this.iterator = new ReportIterator<>(inputStream, parser);
- return this.iterator;
- }
+ this.inputStream = ProtobufUtil.createInputStream(file);
+ return new ReportIterator<>(inputStream, parser);
}
@Override
public void close() throws IOException {
- inputStream.close();
+ if (inputStream != null) {
+ inputStream.close();
+ }
}
public static class ReportIterator<R extends Message> implements Iterator<R> {
import java.util.NoSuchElementException;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.util.Lists.newArrayList;
public class ReportStreamTest {
@Test
public void read_report() throws Exception {
sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
- assertThat(sut).hasSize(1);
- sut.close();
+ assertThat(newArrayList(sut)).hasSize(1);
+
+ assertThat(sut.iterator().next()).isNotNull();
+ // Shoudl not be null as it should return the first element
+ assertThat(sut.iterator().next()).isNotNull();
}
- @Test(expected = IllegalStateException.class)
- public void fail_to_get_iterator_twice() throws Exception {
+ @Test
+ public void next_should_be_reentrant() throws Exception {
sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
- sut.iterator();
+ assertThat(sut).hasSize(1);
- // Fail !
- sut.iterator();
+ assertThat(sut.iterator().next()).isNotNull();
+ assertThat(sut.iterator().next()).isNotNull();
}
@Test(expected = NoSuchElementException.class)
iterator.remove();
}
+ @Test
+ public void not_fail_when_close_without_calling_iterator() throws Exception {
+ sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
+ sut.close();
+ }
+
}