Example usage for org.springframework.batch.item.support AbstractItemCountingItemStreamItemReader AbstractItemCountingItemStreamItemReader

List of usage examples for org.springframework.batch.item.support AbstractItemCountingItemStreamItemReader AbstractItemCountingItemStreamItemReader

Introduction

In this page you can find the example usage for org.springframework.batch.item.support AbstractItemCountingItemStreamItemReader AbstractItemCountingItemStreamItemReader.

Prototype

AbstractItemCountingItemStreamItemReader

Source Link

Usage

From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanRetryTests.java

@Test
public void testRestartAfterFailedWrite() throws Exception {

    factory.setSkipLimit(0);//from   w  w  w .java  2 s.com
    factory.setCommitInterval(3);
    AbstractItemCountingItemStreamItemReader<String> reader = new AbstractItemCountingItemStreamItemReader<String>() {

        private ItemReader<String> reader;

        @Override
        protected void doClose() throws Exception {
            reader = null;
        }

        @Override
        protected void doOpen() throws Exception {
            reader = new ListItemReader<String>(Arrays.asList("a", "b", "c", "d", "e", "f"));
        }

        @Override
        protected String doRead() throws Exception {
            return reader.read();
        }

    };
    // Need to set name or else reader will fail to open
    reader.setName("foo");
    factory.setItemReader(reader);
    factory.setStreams(new ItemStream[] { reader });
    factory.setItemWriter(new ItemWriter<String>() {
        @Override
        public void write(List<? extends String> items) throws Exception {
            if (fail && items.contains("e")) {
                throw new RuntimeException("Planned failure");
            }
            processed.addAll(items);
        }
    });
    factory.setRetryLimit(0);
    Step step = factory.getObject();

    fail = true;
    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);

    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());
    assertEquals(4, stepExecution.getWriteCount());
    assertEquals(6, stepExecution.getReadCount());

    fail = false;
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    stepExecution = new StepExecution(step.getName(), jobExecution);
    stepExecution.setExecutionContext(executionContext);
    repository.add(stepExecution);
    step.execute(stepExecution);

    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    assertEquals(2, stepExecution.getWriteCount());
    assertEquals(2, stepExecution.getReadCount());
}