Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItemReader returning a FlatFileItemReader containing entire lines as strings

Using Spring Batch I am trying to get every line of an input file as a String giving it to the ItemProcessor without any "CSV parsing" in the ItemReader.

I came out with a configuration Java class (using @Configuration and @EnableBatchProcessing) containing the following reader() method which is making the next ItemProcessor to throw a ClassCastException though.

This ItemReader should read an input file and pass to the ItemProcessor every line of the input file as a String.

@Bean
public ItemReader<String> reader() {

    FlatFileItemReader<String> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("data-to-process.txt"));
    reader.setLineMapper(new DefaultLineMapper() {{
        setLineTokenizer(new DelimitedLineTokenizer());
        setFieldSetMapper(new PassThroughFieldSetMapper());
    }});
    return reader;
}

When running the previous code I am getting an exception in the ItemProcessor which is expecting a String from the reader():

    java.lang.ClassCastException: org.springframework.batch.item.file.transform.DefaultFieldSet cannot be cast to java.lang.String

The custom ItemProcessor I wrote is defined as:

    public class MyOwnCustomItemProcessor implements ItemProcessor<String, MyOwnCustomBusinessBean> {

I believe I should use this PassThroughFieldSetMapper in the ItemReader and I would not like to use any kind of tokenizer. According to the documentation I think I must use it and I can not avoid it, but I am keeping getting exceptions thrown.

How can I "transfer" every input line directly as a String to an ItemProcessor e.g. ?

like image 858
TPPZ Avatar asked Feb 20 '14 16:02

TPPZ


1 Answers

Use PassThroughLineMapper if available else

public class PassThroughLineMapper implements LineMapper<String> {
  @Override
  public String mapLine(String line, int lineNumber) throws Exception {
    return line;
  }
}
like image 135
Luca Basso Ricci Avatar answered Nov 14 '22 23:11

Luca Basso Ricci