
com.somospnt.loaderlib.factory.LineMapperFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of loader-lib Show documentation
Show all versions of loader-lib Show documentation
Libreria para hacer loader de archivo a tabla por HTTP
The newest version!
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.somospnt.loaderlib.factory;
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.batch.item.file.LineMapper;
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.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.Assert;
import org.springframework.validation.DataBinder;
public class LineMapperFactory {
public static LineMapper crear(Class clase, String... nombresAtributos) {
verificarAtributosExistenEnClase(clase, nombresAtributos);
DefaultLineMapper lineMapper = new DefaultLineMapper<>();
BeanWrapperFieldSetMapper mapper = new CustomBeanWrapperFieldSetMapper();
mapper.setTargetType(clase);
mapper.setDistanceLimit(0);
lineMapper.setFieldSetMapper(mapper);
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter("|");
tokenizer.setNames(nombresAtributos);
lineMapper.setLineTokenizer(tokenizer);
return lineMapper;
}
private static void verificarAtributosExistenEnClase(Class clase, String... nombresCampos) {
BeanWrapper beanWrapper = new BeanWrapperImpl(clase);
for (String nombreCampo : nombresCampos) {
Assert.isTrue(beanWrapper.isWritableProperty(nombreCampo), "El campo a leer: '" + nombreCampo + "' no existe en la clase " + clase.getName());
}
}
private static class CustomBeanWrapperFieldSetMapper extends BeanWrapperFieldSetMapper {
@Override
protected void initBinder(DataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue("".equals(text) ? null : LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyyMMdd")));
}
});
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue("".equals(text) ? null : text);
}
});
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy