Spring boot and Batch -2

kumar ramanathan
2 min readOct 17, 2023

Stride 2 — Today we are going to create a contact entity, respective service class to read the csv file, remove the records having empty columns.

Step 1: create service class which reads the file and identify the rows which has any missing data and remove the rows from the file and send to store it in the database.

Fields in csv file: firstName, lastName, gender , email, phone

create a package named service and create a service interface name ContactService and its implementation class as ContactServiceImpl

service package and contact service interface and class

ContactServiceimpl serves as a service and the validate file if any of the column in a record is missing we are skipping it.Finally creating a array list and return to the caller.

package com.example.batchapplication.service;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

@Service
public class ContactServiceImpl implements ContactService{

//method validates the input file has any empty columns in any of the rows
//if found remove the row from store it in db
@Override
@Bean
public ArrayList<String> validateFile() throws IOException {
//csv file reader
var filePath = System.getProperty("user.dir") + "/src/main/resources/contacts.csv";
var fileEntries = new ArrayList<String>();
int flag = 0;
try(BufferedReader br = new BufferedReader(new FileReader(filePath))){
String line;
while((line = br.readLine()) != null){
String [] cols = line.split(",");
flag = 0;
for(int i = 0;i < cols.length ; i++ ){
if (cols[i].isEmpty()){
flag = 1;
}
}
if(flag==0){
fileEntries.add(line);
}
}
}
fileEntries.remove(0);
return fileEntries;
}
}
@RestController
public class BatchController {

@Autowired
private ContactService contactService;

@GetMapping("/test")
public String testApi(){
System.out.println("api testing is working fine");
return "I am a rest api ";

}

@GetMapping("/readcsv")
public ArrayList<String> readCSV() throws IOException {
return contactService.validateFile();
}

}
package com.example.batchapplication.service;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

public interface ContactService {
public ArrayList<String > validateFile() throws IOException;
}

Here we have added a readcsv method in controller , that will filter the records if any column have empty data.

Now run the rest api call from talend client or browser , you will get the data as below.

--

--