All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.nicosensei.textbatch.job.Job Maven / Gradle / Ivy

/**
 *
 */
package com.github.nicosensei.textbatch.job;

import java.util.List;

import org.apache.log4j.Level;

import com.github.nicosensei.textbatch.Tool;
import com.github.nicosensei.textbatch.ToolException;


/**
 * @author ngiraud
 *
 */
public abstract class Job extends Thread {


    private InputFileReader input;
    private JobProgress progress;

    protected Tool tool;

    private boolean alive = true;

    protected Job(InputFileReader input, JobProgress progress) {
        this.input = input;
        this.progress = progress;
        this.tool = Tool.getInstance();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void run() {
        while (alive) {

            // Read a section from the input file
            InputFileSection section = null;
            try {
                section = input.readSection();
            } catch (InputFileException e) {
                tool.logError(e);
                break;
            }

            try {
                // Process it
                for (L line : preProcessSection(section)) {
                    processLine(line);
                    progress.notifyLineProcessed(line);
                }

                sectionComplete();
            } catch (ToolException e) {
                handleToolException(e);
            }

            // Stop if there's no more input available
            if (section.noMoreInput()) {
                break;
            }
        }
        if (alive) {
            try {
                jobComplete();
            } catch (ToolException e) {
                handleToolException(e);
            }
        }
    }

    public JobProgress getProgress() {
        return progress;
    }

    protected abstract void processLine(L line) throws ToolException;
    
    /**
     * By default simply return all the lines in the section. Sub-classes can override this 
     * method to perform specific processing (aggregation, filtering).
     * @param section
     * @return
     * @throws ToolException
     */
    protected List preProcessSection(InputFileSection section) throws ToolException {
    	return section.getLines();
    }
    
    protected abstract void sectionComplete() throws ToolException;
    protected abstract void jobComplete() throws ToolException;

    protected void handleToolException(ToolException e) {
        progress.notifyError(e);
        if (Level.FATAL.equals(e.getCriticity())) {
            Tool.getInstance().logInfo(
                    "Fatal error "
                    + e.getClass().getSimpleName());
            this.alive = false;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy