Example usage for org.springframework.batch.core JobInterruptedException JobInterruptedException

List of usage examples for org.springframework.batch.core JobInterruptedException JobInterruptedException

Introduction

In this page you can find the example usage for org.springframework.batch.core JobInterruptedException JobInterruptedException.

Prototype

public JobInterruptedException(String msg) 

Source Link

Usage

From source file:org.springframework.batch.core.job.SimpleStepHandler.java

@Override
public StepExecution handleStep(Step step, JobExecution execution)
        throws JobInterruptedException, JobRestartException, StartLimitExceededException {
    if (execution.isStopping()) {
        throw new JobInterruptedException("JobExecution interrupted.");
    }//www .jav  a 2s .  c o m

    JobInstance jobInstance = execution.getJobInstance();

    StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobInstance, step.getName());
    if (stepExecutionPartOfExistingJobExecution(execution, lastStepExecution)) {
        // If the last execution of this step was in the same job, it's
        // probably intentional so we want to run it again...
        logger.info(String.format(
                "Duplicate step [%s] detected in execution of job=[%s]. "
                        + "If either step fails, both will be executed again on restart.",
                step.getName(), jobInstance.getJobName()));
        lastStepExecution = null;
    }
    StepExecution currentStepExecution = lastStepExecution;

    if (shouldStart(lastStepExecution, execution, step)) {

        currentStepExecution = execution.createStepExecution(step.getName());

        boolean isRestart = (lastStepExecution != null
                && !lastStepExecution.getStatus().equals(BatchStatus.COMPLETED));

        if (isRestart) {
            currentStepExecution.setExecutionContext(lastStepExecution.getExecutionContext());

            if (lastStepExecution.getExecutionContext().containsKey("batch.executed")) {
                currentStepExecution.getExecutionContext().remove("batch.executed");
            }
        } else {
            currentStepExecution.setExecutionContext(new ExecutionContext(executionContext));
        }

        jobRepository.add(currentStepExecution);

        logger.info("Executing step: [" + step.getName() + "]");
        try {
            step.execute(currentStepExecution);
            currentStepExecution.getExecutionContext().put("batch.executed", true);
        } catch (JobInterruptedException e) {
            // Ensure that the job gets the message that it is stopping
            // and can pass it on to other steps that are executing
            // concurrently.
            execution.setStatus(BatchStatus.STOPPING);
            throw e;
        }

        jobRepository.updateExecutionContext(execution);

        if (currentStepExecution.getStatus() == BatchStatus.STOPPING
                || currentStepExecution.getStatus() == BatchStatus.STOPPED) {
            // Ensure that the job gets the message that it is stopping
            execution.setStatus(BatchStatus.STOPPING);
            throw new JobInterruptedException("Job interrupted by step execution");
        }

    }

    return currentStepExecution;
}

From source file:org.springframework.batch.core.step.AbstractStep.java

/**
 * Template method for step execution logic - calls abstract methods for resource initialization (
 * {@link #open(ExecutionContext)}), execution logic ({@link #doExecute(StepExecution)}) and resource closing (
 * {@link #close(ExecutionContext)})./* w  w  w . j a  v a 2 s. co  m*/
 */
@Override
public final void execute(StepExecution stepExecution)
        throws JobInterruptedException, UnexpectedJobExecutionException {

    if (logger.isDebugEnabled()) {
        logger.debug("Executing: id=" + stepExecution.getId());
    }
    stepExecution.setStartTime(new Date());
    stepExecution.setStatus(BatchStatus.STARTED);
    getJobRepository().update(stepExecution);

    // Start with a default value that will be trumped by anything
    ExitStatus exitStatus = ExitStatus.EXECUTING;

    doExecutionRegistration(stepExecution);

    try {
        getCompositeListener().beforeStep(stepExecution);
        open(stepExecution.getExecutionContext());

        try {
            doExecute(stepExecution);
        } catch (RepeatException e) {
            throw e.getCause();
        }
        exitStatus = ExitStatus.COMPLETED.and(stepExecution.getExitStatus());

        // Check if someone is trying to stop us
        if (stepExecution.isTerminateOnly()) {
            throw new JobInterruptedException("JobExecution interrupted.");
        }

        // Need to upgrade here not set, in case the execution was stopped
        stepExecution.upgradeStatus(BatchStatus.COMPLETED);
        if (logger.isDebugEnabled()) {
            logger.debug("Step execution success: id=" + stepExecution.getId());
        }
    } catch (Throwable e) {
        stepExecution.upgradeStatus(determineBatchStatus(e));
        exitStatus = exitStatus.and(getDefaultExitStatusForFailure(e));
        stepExecution.addFailureException(e);
        if (stepExecution.getStatus() == BatchStatus.STOPPED) {
            logger.info(String.format("Encountered interruption executing step %s in job %s : %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName(), e.getMessage()));
            if (logger.isDebugEnabled()) {
                logger.debug("Full exception", e);
            }
        } else {
            logger.error(String.format("Encountered an error executing step %s in job %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }
    } finally {

        try {
            // Update the step execution to the latest known value so the
            // listeners can act on it
            exitStatus = exitStatus.and(stepExecution.getExitStatus());
            stepExecution.setExitStatus(exitStatus);
            exitStatus = exitStatus.and(getCompositeListener().afterStep(stepExecution));
        } catch (Exception e) {
            logger.error(String.format("Exception in afterStep callback in step %s in job %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        try {
            getJobRepository().updateExecutionContext(stepExecution);
        } catch (Exception e) {
            stepExecution.setStatus(BatchStatus.UNKNOWN);
            exitStatus = exitStatus.and(ExitStatus.UNKNOWN);
            stepExecution.addFailureException(e);
            logger.error(String.format(
                    "Encountered an error saving batch meta data for step %s in job %s. "
                            + "This job is now in an unknown state and should not be restarted.",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        stepExecution.setEndTime(new Date());
        stepExecution.setExitStatus(exitStatus);

        try {
            getJobRepository().update(stepExecution);
        } catch (Exception e) {
            stepExecution.setStatus(BatchStatus.UNKNOWN);
            stepExecution.setExitStatus(exitStatus.and(ExitStatus.UNKNOWN));
            stepExecution.addFailureException(e);
            logger.error(String.format(
                    "Encountered an error saving batch meta data for step %s in job %s. "
                            + "This job is now in an unknown state and should not be restarted.",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        try {
            close(stepExecution.getExecutionContext());
        } catch (Exception e) {
            logger.error(String.format("Exception while closing step execution resources in step %s in job %s",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
            stepExecution.addFailureException(e);
        }

        doExecutionRelease();

        if (logger.isDebugEnabled()) {
            logger.debug("Step execution complete: " + stepExecution.getSummary());
        }
    }
}

From source file:org.springframework.batch.core.step.tasklet.SystemCommandTasklet.java

/**
 * Execute system command and map its exit code to {@link ExitStatus} using
 * {@link SystemProcessExitCodeMapper}./*from   w ww .j a v  a  2 s.  com*/
 */
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    FutureTask<Integer> systemCommandTask = new FutureTask<Integer>(new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            Process process = Runtime.getRuntime().exec(command, environmentParams, workingDirectory);
            return process.waitFor();
        }

    });

    long t0 = System.currentTimeMillis();

    taskExecutor.execute(systemCommandTask);

    while (true) {
        Thread.sleep(checkInterval);//moved to the end of the logic

        if (stoppable) {
            JobExecution jobExecution = jobExplorer
                    .getJobExecution(chunkContext.getStepContext().getStepExecution().getJobExecutionId());

            if (jobExecution.isStopping()) {
                stopped = true;
            }
        }

        if (systemCommandTask.isDone()) {
            contribution.setExitStatus(systemProcessExitCodeMapper.getExitStatus(systemCommandTask.get()));
            return RepeatStatus.FINISHED;
        } else if (System.currentTimeMillis() - t0 > timeout) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new SystemCommandException("Execution of system command did not finish within the timeout");
        } else if (execution.isTerminateOnly()) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new JobInterruptedException(
                    "Job interrupted while executing system command '" + command + "'");
        } else if (stopped) {
            systemCommandTask.cancel(interruptOnCancel);
            contribution.setExitStatus(ExitStatus.STOPPED);
            return RepeatStatus.FINISHED;
        }
    }
}

From source file:org.springframework.batch.core.step.ThreadStepInterruptionPolicy.java

/**
 * Returns if the current job lifecycle has been interrupted by checking if
 * the current thread is interrupted.//from  w w  w . j av  a 2  s . c  o m
 */
@Override
public void checkInterrupted(StepExecution stepExecution) throws JobInterruptedException {

    if (isInterrupted(stepExecution)) {
        throw new JobInterruptedException("Job interrupted status detected.");
    }

}