2

My XML Step declaration

<step id="MongoDbLoadDataStep" next="checkStatusStep">
    <tasklet>
        <chunk reader="MongoReader" writer="MongoWriter" commit-interval="5"/>
    </tasklet>
</step>

A reader has only one method read and no chance to increase reads counter or to get access to Spring StepContribution instance. So I need to find a way how to provide a mechanism that could allow me to increment step reads counter. In Tasklet we have very convenient method:

RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)

But in XML there is only default Tasklet which is managed by Spring internals. Any ideas how can I do that?

PS

I can't modify XML Batch configuration

user5490040
  • 145
  • 1
  • 6

1 Answers1

3

You can implement an ItemReadListener to increment a counter after each read. And a StepExecutionListener to store the result in the context (omitted empty methods) :

public class ItemReadCountListener implements ItemReadListener<T>, StepExecutionListener {

    private Integer count = 0;

    @Override
    public void afterRead(T item) {
        count++; // Increment counter
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
       stepExecution.getJobExecution().getExecutionContext().put("ITEM_READ_COUNT", count); // Store counter
    }
}

Add it to your chunk :

<batch:chunk>
    <batch:listeners merge="true">
         <batch:listener>
              <bean class="xx.xx.xx.ItemReadCountListener" />
         </batch:listener>
    </batch:listeners>
</batch:chunk>
Thrax
  • 1,926
  • 1
  • 17
  • 32
  • @Finkelson `stepExecution` in the `afterStep` method does the same. That is to say, you can acess the read counter stored in the `JobExecutionContext` from anywhere by calling `get("ITEM_READ_COUNT")` – Thrax Jan 12 '16 at 10:38
  • If it chunked, should I use AtomicInteger as counter instead of Integer? – user5490040 Jan 12 '16 at 10:47
  • @user5490040 I didn't know about AtomicInteger, I always used Integer up until now. I guess both would work. I'm not sure about the behaviour of the counter during parallelization. – Thrax Jan 12 '16 at 10:50