View Javadoc
1   /*
2    *    Copyright 2016-2025 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package examples.springbatch.common;
17  
18  import org.springframework.batch.core.StepExecution;
19  import org.springframework.batch.core.annotation.BeforeChunk;
20  import org.springframework.batch.core.annotation.BeforeStep;
21  import org.springframework.batch.core.scope.context.ChunkContext;
22  import org.springframework.batch.item.ExecutionContext;
23  import org.springframework.batch.item.ItemProcessor;
24  import org.springframework.stereotype.Component;
25  
26  @Component
27  public class PersonProcessor implements ItemProcessor<PersonRecord, PersonRecord> {
28  
29      private ExecutionContext executionContext;
30  
31      @Override
32      public PersonRecord process(PersonRecord person) {
33          incrementRowCount();
34  
35          PersonRecord transformed = new PersonRecord();
36          transformed.setId(person.getId());
37          transformed.setFirstName(person.getFirstName().toUpperCase());
38          transformed.setLastName(person.getLastName().toUpperCase());
39          return transformed;
40      }
41  
42      @BeforeStep
43      public void beforeStep(StepExecution stepExecution) {
44          executionContext = stepExecution.getExecutionContext();
45      }
46  
47      @BeforeChunk
48      public void beforeChunk(ChunkContext chunkContext) {
49          incrementChunkCount();
50      }
51  
52      private void incrementRowCount() {
53          executionContext.putInt("row_count",
54                  executionContext.getInt("row_count", 0) + 1);
55      }
56  
57      private void incrementChunkCount() {
58          executionContext.putInt("chunk_count",
59                  executionContext.getInt("chunk_count", 0) + 1);
60      }
61  }