Java Reference
In-Depth Information
have the ability to map FieldSets to their respective objects, you need to be able to tokenize the lines in
the file into the FieldSets. Unfortunately, in this case, it's not quite that simple.
In the example in Chapter 7, you used a file that contained a prefix on each row. This allowed you to
use Spring Batch's PatternMatchingCompositeLineMapper to specify a pattern that identifies each that
LineTokenizer uses to parse the record. However, PatternMatchingCompositeLineMapper's pattern-
matching ability is limited. It allows for only the verification of string literals and two types of wildcards
( ? for a single character and * for one or more characters). The records contained in your input file are
too complex to be mapped using this form of pattern matching. Because of this, you need to create your
own version of PatternMatchingCompositeLineMapper that applies a true regular expression to each
line to determine what LineTokenizer (and subsequently, which FieldSetMapper) to use. Listing 10-11
shows RegularExpressionLineMapper .
Listing 10-11. RegularExpressionLineMapper
package com.apress.springbatch.statement.reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.item.file.transform.LineTokenizer;
import org.springframework.beans.factory.InitializingBean;
public class RegularExpressionLineMapper implements LineMapper<Object>, InitializingBean {
private Map<String, LineTokenizer> tokenizers;
private Map<String, FieldSetMapper<Object>> mappers;
private Map<Pattern, LineTokenizer> patternTokenizers;
private Map<LineTokenizer, FieldSetMapper<Object>> patternMappers;
public Object mapLine(String input, int rowCount) throws Exception {
LineTokenizer tokenizer = findTokenizer(input);
FieldSet fields = tokenizer.tokenize(input);
FieldSetMapper<Object> mapper = patternMappers.get(tokenizer);
if(mapper != null) {
return mapper.mapFieldSet(fields);
throw new ParseException("Unable to parse the input " + input);
private LineTokenizer findTokenizer(String input) {
LineTokenizer tokenizer = null;
Search WWH ::

Custom Search