EnrichCatalogExtrasItemReader.java

package com.sintia.ffl.admin.optique.catalogue.batch.reader.enrichcatalog;

import com.sintia.ffl.admin.optique.catalogue.models.ExtrasCSV;
import com.sintia.ffl.admin.optique.catalogue.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;

import java.nio.file.Paths;

/**
 * Read raw data from a csv file and convert them to {@link ExtrasCSV}
 *
 * @author jumazet
 */
@Component
@StepScope
@Slf4j
public class EnrichCatalogExtrasItemReader extends FlatFileItemReader<ExtrasCSV> {

	private String[] columnsName = new String[] { "maker", "provider", "extrasCode", "extrasName", "extrasType" };

	public EnrichCatalogExtrasItemReader(
		@Value("#{jobParameters[extrasFileName]}") String fileName, @Value("${local.resources.directory}") String localDirectory,
		@Value("${catalog.to.enrich.directory}") String specificDirectory) {
		super();
		this.setResource(new FileSystemResource(Paths.get(localDirectory).resolve(specificDirectory).resolve(fileName).toString()));

		DefaultLineMapper<ExtrasCSV> lineMapper = new DefaultLineMapper<>();

		DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
		tokenizer.setNames(columnsName);
		tokenizer.setDelimiter(Constants.CSV_SEPARATOR);
		lineMapper.setLineTokenizer(tokenizer);

		BeanWrapperFieldSetMapper<ExtrasCSV> fieldMapper = new BeanWrapperFieldSetMapper<>();
		fieldMapper.setTargetType(ExtrasCSV.class);
		lineMapper.setFieldSetMapper(fieldMapper);

		// Skip the first line (ie the header line)
		this.setLinesToSkip(1);
		this.setEncoding("UTF-8");
		this.setLineMapper(lineMapper);
	}

	@Override
	protected void doClose()
		throws Exception {
		try {
			super.doClose();
		}
		catch (Exception e) {
			log.error("Erreur à la fermeture", e);
			throw e;
		}
	}
}