EnrichedGlassesItemWriter.java

package com.sintia.ffl.admin.optique.catalogue.batch.writer;

import com.sintia.ffl.admin.optique.catalogue.models.EnrichedGlassesCSV;
import com.sintia.ffl.admin.optique.catalogue.util.Constants;
import com.sintia.ffl.admin.optique.catalogue.util.FileNameNotMatchException;
import com.sintia.ffl.admin.optique.catalogue.util.FileUtil;
import com.sintia.ffl.admin.optique.services.services.FabricantService;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;

import java.nio.file.Paths;

/**
 * Take in input a data in the format {@link EnrichedGlassesCSV} and save them
 * in a CSV file
 *
 * @author jumazet
 */
@Component
@StepScope
public class EnrichedGlassesItemWriter extends FlatFileItemWriter<EnrichedGlassesCSV> {

	private static final String HEADER = "Code fabricant;Code Fournisseur;Code verre;Classe verre;Classe verre référentiel;Nom verre;Nom verre référentiel;Géométrie;Géométrie référentiel;Matière;Matière référentiel;Asphérique;Asphérique référentiel;Durci;Durci référentiel;Anti-reflet;Anti-reflet référentiel;Photochromique;Photochromique référentiel;Indice de réfraction;Indice de réfraction référentiel;Teinté;Teinté référentiel;Code action;Date de péremption;Date debut validite;Code action delta;Correction données catalogue;Commentaire";

	public EnrichedGlassesItemWriter(@Value("#{jobParameters[glassesFileName]}") String fileName,
			@Value("${local.resources.directory}") String localDirectory, @Autowired FileUtil fileUtil,
			@Autowired FabricantService fabricantService,
			@Value("${catalog.enriched.directory}") String enrichedCatalogWithAgreementDirectory,
			@Value("${catalog.unlist.directory}") String enrichedCatalogWithoutAgreementDirectory)
			throws FileNameNotMatchException {

		String resultFileName = fileUtil.convertToCorrectedGlassessFileName(fileName);

		String cOptoCodeFabricant = fileUtil.extractMakerFromGlassesFileName(fileName, Constants.INITAL_FILE);
		String resourcePath = "";
		if (fabricantService.isMakerWithAgreement(cOptoCodeFabricant)) {
			resourcePath = Paths.get(localDirectory)
					.resolve(enrichedCatalogWithAgreementDirectory)
					.resolve(resultFileName)
					.toString();
		} else {
			resourcePath = Paths.get(localDirectory)
					.resolve(enrichedCatalogWithoutAgreementDirectory)
					.resolve(resultFileName)
					.toString();
		}

		this.setResource(new FileSystemResource(resourcePath));
		this.setLineAggregator(new EnrichedGlassesLineAggregator());
		this.setShouldDeleteIfExists(true);

		StringHeaderWriter header = new StringHeaderWriter(HEADER);
		this.setHeaderCallback(header);
	}

}