Reputation: 4891
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. ?
Upvotes: 5
Views: 9344
Reputation: 4891
I am adding also a workaround I found in the meanwhile (using FieldSet
as a input parameter of the ItemReader
and the ItemProcessor
), even if @bellabax provided a better solution.
Check how I used the objects of type FieldSet
.
The ItemReader
:
@Bean
public ItemReader<FieldSet> reader() {
FlatFileItemReader<FieldSet> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("data-to-process.txt"));
reader.setLineMapper(new DefaultLineMapper() {{
setLineTokenizer(new DelimitedLineTokenizer());
setFieldSetMapper(new PassThroughFieldSetMapper() {{
}});
}});
return reader;
}
The ItemProcessor
in the Spring Batch Configuration class:
@Bean
public ItemProcessor<FieldSet, MyOwnCustomBusinessBean> processor() {
return new MyOwnCustomItemProcessor();
}
The ItemProcessor
:
public class MyOwnCustomItemProcessor implements ItemProcessor<FieldSet, MyOwnCustomBusinessBean> {
@Override
public MyOwnCustomBusinessBean process(FieldSet originalInputLineFromInputFile) throws Exception {
String originalInputLine = originalInputLineFromInputFile.getValues()[0];
[...]
Upvotes: 0
Reputation: 18413
Use PassThroughLineMapper if available else
public class PassThroughLineMapper implements LineMapper<String> {
@Override
public String mapLine(String line, int lineNumber) throws Exception {
return line;
}
}
Upvotes: 7