cdc.impex.imports.BatchSheetImporter Maven / Gradle / Ivy
package cdc.impex.imports;
import cdc.impex.templates.SheetTemplate;
import cdc.impex.templates.SheetTemplateInstance;
import cdc.issues.Issue;
import cdc.issues.IssuesHandler;
import cdc.util.lang.Checks;
/**
* Utility class that implements SheetImporter, delegating all the work, and adds batch notifications.
*
* This class can be used to commit data every batch size rows.
*
* @author Damien Carbonne
*/
public class BatchSheetImporter implements SheetImporter {
private final SheetImporter delegate;
private int batchSize = -1;
private int lastBatch = -1;
private int lastData = -1;
private boolean executing = false;
public BatchSheetImporter(SheetImporter delegate) {
this.delegate = Checks.isNotNull(delegate, "delegate");
}
public SheetImporter getDelegate() {
return delegate;
}
public final int getBatchSize() {
return batchSize;
}
/**
* Sets the batch size.
*
* WARNING: MUST not be called during execution.
*
* @param batchSize The batch size. If {@code batchSize <= 0}, batch is never called.
* @return This object.
* @throws AssertionError If this method is called during execution.
*/
public BatchSheetImporter setBatchSize(int batchSize) {
Checks.assertFalse(executing, "Cannot call setBatchSize during execution.");
this.batchSize = batchSize;
return this;
}
/**
* Method that is invoked every batch size data in a sheet,
* and if necessary when ending the sheet.
*
* Its default implementation does nothing and should be overridden.
*/
public void batch() {
// Do nothing
}
@Override
public final void beginSheetImport(String systemId,
String sheetName,
SheetTemplate template,
IssuesHandler issuesHandler) {
executing = true;
lastBatch = -1;
lastData = -1;
delegate.beginSheetImport(systemId, sheetName, template, issuesHandler);
}
@Override
public final void importHeader(SheetTemplateInstance templateInstance,
IssuesHandler issuesHandler) {
delegate.importHeader(templateInstance, issuesHandler);
}
@Override
public final void importRow(ImportRow row,
IssuesHandler issuesHandler) {
delegate.importRow(row, issuesHandler);
if (batchSize > 0 && (row.getNumber() - 1) % batchSize == 0) {
batch();
lastBatch = row.getNumber();
}
lastData = row.getNumber();
}
@Override
public final void endSheetImport(String systemId,
String sheetName,
SheetTemplateInstance templateInstance,
IssuesHandler issuesHandler) {
if (batchSize > 0 && lastBatch != lastData) {
batch();
lastBatch = lastData;
}
delegate.endSheetImport(systemId, sheetName, templateInstance, issuesHandler);
executing = false;
}
}