Java Reference
In-Depth Information
}
}
Skipping records is a common practice in batch processing. It allows what is typically a much larger
process than a single record to continue with minimal impact. Once you can skip a record that has an
error, you may want to do something additional like log it for future evaluation. The next section
discusses an approach for just that.
Logging Invalid Records
While skipping problematic records is a useful tool, by itself it can raise an issue. In some scenarios, the
ability to skip a record is okay. Say you are mining data and come across something you can't resolve; it's
probably okay to skip it. However, when you get into situations where money is involved, say when
processing transactions, just skipping a record probably will not be a robust enough solution. In cases
like these, it is helpful to be able to log the record that was the cause of the error. In this section, you will
look at using an ItemListener to record records that were invalid.
The ItemReadListener interface consists of three methods: beforeRead, afterRead, and onReadError.
For the case of logging invalid records as they are read in, you can use the ItemListenerSupport class and
override the onReadError to log what happened. It's important to point out that Spring Batch does a
good job building its Exceptions for file parsing to inform you of what happened and why. On the
database side, things are a little less in the framework's hands as most of the actual database work is
done by other frameworks (Spring itself, Hibernate, etc). It is important that as you develop your own
processing (custom ItemReaders, RowMappers, etc) that you include enough detail for you to diagnose
the issue from the Exception itself.
In this example, you will read data in from the Customer file from the beginning of the chapter.
When an Exception is thrown during input, you will log the record that caused the exception and the
exception itself. To do this, the CustomerItemListener will take the exception thrown and if it is a
FlatFileParseException, you will have access to the record that caused the issue and information on what
went wrong. Listing 7-64 shows the CustomerItemListener.
Listing 7-64. CustomerItemListener
package com.apress.springbatch.chapter7;
import org.apache.log4j.Logger;
import org.springframework.batch.core.listener.ItemListenerSupport;
import org.springframework.batch.item.file.FlatFileParseException;
public class CustomerItemListener extends
ItemListenerSupport<Customer, Customer> {
private Logger logger = Logger.getLogger(CustomerItemListener.class);
@Override
public void onReadError(Exception e) {
if(e instanceof FlatFileParseException) {
FlatFileParseException ffpe = (FlatFileParseException) e;
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("An error occured while processing the " +
ffpe.getLineNumber() +
 
Search WWH ::




Custom Search