Tuesday, 1 December 2020

Spring Batch: Read data from csv file

In this post, I am going to explain how to read data from a csv file.

 

Using FlatFileItemReader we can read data from a file.

 

Step 1: Create emps.csv file in src/main/respurces/csv folder.

 

emps.csv

 

id,firstName,lastName
1,Ram,Gurram
2,Lakshman,Ponnam
3,Gopi,Battu
4,Sailu,Nava
5,Venkat,Dokku
6,Harini,G
7,Sudheer,Ganji
8,Joel,Chelli
9,Jaideep,Geera

 

Step 2: Define Employee class that holds csv record

public class Employee {
	private int id;
	private String firstName;
	private String lastName;
	.....
	.....
}

 

Step 3: Write Employee field mapper that maps a csv employee record to Employee instance.

public class EmployeeFieldSetMapper implements FieldSetMapper<Employee> {

	@Override
	public Employee mapFieldSet(FieldSet fieldSet) throws BindException {

		Employee emp = new Employee();

		emp.setId(fieldSet.readInt("id"));
		emp.setFirstName(fieldSet.readString("firstName"));
		emp.setLastName(fieldSet.readString("lastName"));

		return emp;
	}

}

 

Step 4: Define FlatFileItemReader bean.

@Bean
public FlatFileItemReader<Employee> reader() {
	FlatFileItemReader<Employee> flatFileItemReader = new FlatFileItemReader<>();

	flatFileItemReader.setLinesToSkip(1);
	flatFileItemReader.setResource(new ClassPathResource("/csv/emps.csv"));

	DefaultLineMapper<Employee> empDefaultLineMapper = new DefaultLineMapper<>();
	DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
	lineTokenizer.setNames(new String[] { "id", "firstName", "lastName" });

	empDefaultLineMapper.setLineTokenizer(lineTokenizer);
	empDefaultLineMapper.setFieldSetMapper(new EmployeeFieldSetMapper());
	empDefaultLineMapper.afterPropertiesSet();

	flatFileItemReader.setLineMapper(empDefaultLineMapper);

	return flatFileItemReader;
}

 

Step 5: Define a step using FlatFileItemReader bean.

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1").chunk(5).reader(reader()).writer(emps -> {
		for (Object emp : emps) {
			System.out.println(emp);
		}
	}).build();
}

 

Find the below working application.

 

Step 1: Create new maven project ‘file-read-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>file-read-demo</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-core -->
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>
</project>

Step 3: Create application.properties file under src/main/resources folder.

 

application.properties

logging.level.root=ERROR
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

Step 4: Create emps.csv file under src/main/resources/csv folder.

 

emps.csv

id,firstName,lastName
1,Ram,Gurram
2,Lakshman,Ponnam
3,Gopi,Battu
4,Sailu,Nava
5,Venkat,Dokku
6,Harini,G
7,Sudheer,Ganji
8,Joel,Chelli
9,Jaideep,Geera

Step 5: Create package ‘com.sample.app.model’ and define Employee class.

 

Employee.java

package com.sample.app.model;

public class Employee {
	private int id;
	private String firstName;
	private String lastName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=");
		builder.append(id);
		builder.append(", firstName=");
		builder.append(firstName);
		builder.append(", lastName=");
		builder.append(lastName);
		builder.append("]");
		return builder.toString();
	}

}

Step 6: Create package ‘com.sample.app.mappers’ and define EmployeeFieldSetMapper.

 

EmployeeFieldSetMapper.java

package com.sample.app.mappers;

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

import com.sample.app.model.Employee;

public class EmployeeFieldSetMapper implements FieldSetMapper<Employee> {

	@Override
	public Employee mapFieldSet(FieldSet fieldSet) throws BindException {

		Employee emp = new Employee();

		emp.setId(fieldSet.readInt("id"));
		emp.setFirstName(fieldSet.readString("firstName"));
		emp.setLastName(fieldSet.readString("lastName"));

		return emp;
	}

}

Step 7: Create package ‘com.sample.app.configuration’ and define EmployeeConfiguration.

 

EmployeeConfiguration.java

package com.sample.app.configuration;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;

import com.sample.app.mappers.EmployeeFieldSetMapper;
import com.sample.app.model.Employee;

@Configuration
@EnableBatchProcessing
public class JobConfiguration {
	@Autowired
	private JobBuilderFactory jobBuilderFactory;

	@Autowired
	private StepBuilderFactory stepBuilderFactory;

	@Bean
	public FlatFileItemReader<Employee> reader() {
		FlatFileItemReader<Employee> flatFileItemReader = new FlatFileItemReader<>();

		flatFileItemReader.setLinesToSkip(1);
		flatFileItemReader.setResource(new ClassPathResource("/csv/emps.csv"));

		DefaultLineMapper<Employee> empDefaultLineMapper = new DefaultLineMapper<>();
		DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
		lineTokenizer.setNames(new String[] { "id", "firstName", "lastName" });

		empDefaultLineMapper.setLineTokenizer(lineTokenizer);
		empDefaultLineMapper.setFieldSetMapper(new EmployeeFieldSetMapper());
		empDefaultLineMapper.afterPropertiesSet();

		flatFileItemReader.setLineMapper(empDefaultLineMapper);

		return flatFileItemReader;
	}

	@Bean
	public Step step1() {
		return this.stepBuilderFactory.get("step1").chunk(5).reader(reader()).writer(emps -> {
			for (Object emp : emps) {
				System.out.println(emp);
			}
		}).build();
	}

	@Bean
	public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) {

		return jobBuilderFactory.get("My-First-Job").start(step1()).build();
	}

}

Step 8: Create App.java

 

App.java

package com.sample.app;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableBatchProcessing
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

Total project structure looks like below.



Run App.java, you will see below messages in console.

Employee [id=1, firstName=Ram, lastName=Gurram]
Employee [id=2, firstName=Lakshman, lastName=Ponnam]
Employee [id=3, firstName=Gopi, lastName=Battu]
Employee [id=4, firstName=Sailu, lastName=Nava]
Employee [id=5, firstName=Venkat, lastName=Dokku]
Employee [id=6, firstName=Harini, lastName=G]
Employee [id=7, firstName=Sudheer, lastName=Ganji]
Employee [id=8, firstName=Joel, lastName=Chelli]
Employee [id=9, firstName=Jaideep, lastName=Geera]

You can download complete working application from this link.

https://github.com/harikrishna553/springboot/tree/master/batch/file-read-demo


 

Previous                                                    Next                                                    Home

Spring Batch : Basic Exception Handling

 

There are multiple ways to handle exception in Spring Batch. In this post, I am going to show the basic one.

 

Spring Batch has a JobRepository, which keep track of the job and steps statuses. When a  job failed, on restart of the spring batch picks the job where it is left previously.

 

Using 'ExecutionContext' of the step, lets track the status of step.

 

For example, I define a tasklet, which set 'step-successful' flag to 1 on its first execution and immediately throws an exception. When the Job is restarted, then application checks the flag 'step-successful' and if it exist then it finishes the step. This is one of the way to control exception handling.

 

@Bean
public Tasklet task1() {
  Tasklet tasklet = new Tasklet() {

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

      ExecutionContext stepExecutionContext = chunkContext.getStepContext().getStepExecution()
          .getExecutionContext();

      if (stepExecutionContext.containsKey("step-successful")) {
        System.out.println("Step 1: Found the key 'step-successful'");
        return RepeatStatus.FINISHED;
      }
      System.out.println("Executing step 1 for first time");
      stepExecutionContext.put("step-successful", 1);
      throw new RuntimeException("Step1 failed to execute");

    }

  };
  return tasklet;
}

 

Find the below working application.

 

Step 1: Create new maven project ‘exception-handling-hello-world’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>exception-handling-hello-world</artifactId>
  <version>1</version>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-core -->
    <dependency>
      <groupId>org.springframework.batch</groupId>
      <artifactId>spring-batch-core</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>



  </dependencies>
</project>

 

Step 3: Create new package ‘com.sample.app.configuration’ and define JobConfiguration.

 

JobConfiguration.java

 

package com.sample.app.configuration;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableBatchProcessing
public class JobConfiguration {
  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Autowired
  private StepBuilderFactory stepBuilderFactory;

  @Bean
  public Tasklet task1() {
    Tasklet tasklet = new Tasklet() {

      @Override
      public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

        ExecutionContext stepExecutionContext = chunkContext.getStepContext().getStepExecution()
            .getExecutionContext();

        if (stepExecutionContext.containsKey("step-successful")) {
          System.out.println("Step 1: Found the key 'step-successful'");
          return RepeatStatus.FINISHED;
        }
        System.out.println("Executing step 1 for first time");
        stepExecutionContext.put("step-successful", 1);
        throw new RuntimeException("Step1 failed to execute");

      }

    };
    return tasklet;
  }

  @Bean
  public Tasklet task2() {
    Tasklet tasklet = new Tasklet() {

      @Override
      public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

        ExecutionContext stepExecutionContext = chunkContext.getStepContext().getStepExecution()
            .getExecutionContext();

        if (stepExecutionContext.containsKey("step-successful")) {
          System.out.println("Step 2: Found the key 'step-successful'");
          return RepeatStatus.FINISHED;
        }
        System.out.println("Executing step 2 for first time");
        stepExecutionContext.put("step-successful", 1);
        throw new RuntimeException("Step2 failed to execute");

      }

    };
    return tasklet;
  }

  @Bean
  public Step step1() throws Exception {
    return this.stepBuilderFactory.get("step1").tasklet(task1()).build();
  }

  @Bean
  public Step step2() throws Exception {
    return this.stepBuilderFactory.get("step2").tasklet(task2()).build();
  }

  @Bean
  public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager)
      throws Exception {

    return jobBuilderFactory.get("My-First-Job").start(step1()).next(step2()).build();
  }

}

 

Step 4: Define main application class.

 

App.java

 

package com.sample.app;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableBatchProcessing
@SpringBootApplication
public class App {

  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

 

Total project structure looks like below.


 

 

Run App.java.

 

You will see below messages in console.

Executing step 1 for first time
2020-04-14 12:12:28.976 ERROR 56871 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step1 in job My-First-Job

java.lang.RuntimeException: Step1 failed to execute
  at com.sample.app.configuration.JobConfiguration$1.execute(JobConfiguration.java:44) ~[classes/:na]
  at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
  ......
  ......

Open the url ‘http://localhost:8080/h2’ in browser. Connect to H2 database using username ‘krishna’ and password ‘password123’.

 

See the contents of 'BATCH_STEP_EXECUTION_CONTEXT' table

 

You will see a record with following SHORT_CONTEXT.

{
  "batch.taskletType": "com.sample.app.configuration.JobConfiguration$1",
  "step-successful": 1,
  "batch.stepType": "org.springframework.batch.core.step.tasklet.TaskletStep"
}

As you observe above json, you can see the key "step-successful".

 

Stop the application and rerun.

Step 1: Found the key 'step-successful'
Executing step 2 for first time
2020-04-14 12:15:15.856 ERROR 56903 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step2 in job My-First-Job

java.lang.RuntimeException: Step2 failed to execute
  at com.sample.app.configuration.JobConfiguration$2.execute(JobConfiguration.java:68) ~[classes/:na]
  .....
  .....

Stop the application and rerun, you will see below message in console.
Step 2: Found the key 'step-successful'

You can download complete working application form this link.

https://github.com/harikrishna553/springboot/tree/master/batch/exception-handling-hello-world 

 

 



 

 

 

 

Previous                                                    Next                                                    Home