|
| 1 | +package org.baeldung.taskletsvschunks.tasklets; |
| 2 | + |
| 3 | +import org.baeldung.taskletsvschunks.model.Line; |
| 4 | +import org.slf4j.Logger; |
| 5 | +import org.slf4j.LoggerFactory; |
| 6 | +import org.springframework.batch.core.ExitStatus; |
| 7 | +import org.springframework.batch.core.StepContribution; |
| 8 | +import org.springframework.batch.core.StepExecution; |
| 9 | +import org.springframework.batch.core.StepExecutionListener; |
| 10 | +import org.springframework.batch.core.scope.context.ChunkContext; |
| 11 | +import org.springframework.batch.core.step.tasklet.Tasklet; |
| 12 | +import org.springframework.batch.item.ExecutionContext; |
| 13 | +import org.springframework.batch.repeat.RepeatStatus; |
| 14 | + |
| 15 | +import java.time.LocalDate; |
| 16 | +import java.time.temporal.ChronoUnit; |
| 17 | +import java.util.List; |
| 18 | + |
| 19 | +public class LinesProcessor implements Tasklet, StepExecutionListener { |
| 20 | + |
| 21 | + private final Logger logger = LoggerFactory.getLogger(LinesProcessor.class); |
| 22 | + |
| 23 | + private List<Line> lines; |
| 24 | + |
| 25 | + @Override |
| 26 | + public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { |
| 27 | + for (Line line : lines) { |
| 28 | + long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); |
| 29 | + logger.debug("Calculated age " + age + " for line " + line.toString()); |
| 30 | + line.setAge(age); |
| 31 | + } |
| 32 | + return RepeatStatus.FINISHED; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void beforeStep(StepExecution stepExecution) { |
| 37 | + ExecutionContext executionContext = stepExecution |
| 38 | + .getJobExecution() |
| 39 | + .getExecutionContext(); |
| 40 | + this.lines = (List<Line>) executionContext.get("lines"); |
| 41 | + logger.debug("Lines Processor initialized."); |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public ExitStatus afterStep(StepExecution stepExecution) { |
| 46 | + logger.debug("Lines Processor ended."); |
| 47 | + return ExitStatus.COMPLETED; |
| 48 | + } |
| 49 | +} |
0 commit comments