Example usage for org.springframework.batch.core BatchStatus STARTING

List of usage examples for org.springframework.batch.core BatchStatus STARTING

Introduction

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

Prototype

BatchStatus STARTING

To view the source code for org.springframework.batch.core BatchStatus STARTING.

Click Source Link

Usage

From source file:com.inkubator.hrm.web.workingtime.WtPeriodEmpDetailController.java

public void doCalculateAttendanceRealization() {
    /** to cater prevent multiple click, that will make batch execute multiple time. 
     *  please see onComplete method that will set jobExecution == null */
    if (jobExecution == null) {
        try {/*from  ww w.  java2s.  c  o  m*/

            long sleepVariable = tempAttendanceRealizationService
                    .getTotalListTempAttendanceRealizationViewModelByWtPeriodId(searchParameter,
                            model.getWtPeriodId().longValue())
                    * 3;
            JobParameters jobParameters = new JobParametersBuilder()
                    .addDate("periodUntillDate", model.getUntilPeriode())
                    .addString("createdBy", UserInfoUtil.getUserName()).addDate("createdOn", new Date())
                    .addLong("wtPeriodId", model.getWtPeriodId().longValue()).toJobParameters();
            jobExecution = jobLauncherAsync.run(jobTempAttendanceRealizationCalculation, jobParameters);

            int i = 0;
            while (true) {
                if (jobExecution.getStatus() == BatchStatus.STARTED
                        || jobExecution.getStatus() == BatchStatus.STARTING) {
                    if (i <= 85) {
                        setProgress(i++);
                    }
                    try {
                        Thread.sleep(sleepVariable);
                    } catch (InterruptedException e) {
                    }
                } else {
                    setProgress(100);
                    break;
                }
            }

        } catch (BussinessException ex) {
            jobExecution.setExitStatus(ExitStatus.FAILED);
            jobExecution.setStatus(BatchStatus.FAILED);
            jobExecution.addFailureException(ex);
            MessagesResourceUtil.setMessages(FacesMessage.SEVERITY_ERROR, "global.error",
                    ex.getErrorKeyMessage(),
                    FacesUtil.getSessionAttribute(HRMConstant.BAHASA_ACTIVE).toString());
        } catch (Exception ex) {
            LOGGER.error("Error ", ex);
        }
    }
}

From source file:com.inkubator.hrm.web.payroll.PaySalaryExecuteController.java

public void doCalculatePayroll() {
    if (payrollCalculationDate == null) {
        MessagesResourceUtil.setMessagesFlas(FacesMessage.SEVERITY_ERROR, "global.error",
                "salaryCalculation.payroll_date_should_be_filled",
                FacesUtil.getSessionAttribute(HRMConstant.BAHASA_ACTIVE).toString());
        FacesContext.getCurrentInstance().validationFailed();
    }/*from   w w  w .  j  a va  2 s .  c  o  m*/

    /** to cater prevent multiple click, that will make batch execute multiple time. 
     *  please see onComplete method that will set jobExecution == null */
    if (jobExecution == null && payrollCalculationDate != null) {
        try {
            long sleepVariable = empDataService.getTotalEmpDataNotTerminate() * 3;

            JobParameters jobParameters = new JobParametersBuilder()
                    .addDate("payrollCalculationDate", payrollCalculationDate)
                    .addDate("startPeriodDate", wtPeriodePayroll.getFromPeriode())
                    .addDate("endPeriodDate", wtPeriodePayroll.getUntilPeriode())
                    .addString("createdBy", UserInfoUtil.getUserName()).addDate("createdOn", new Date())
                    .toJobParameters();
            jobExecution = jobLauncherAsync.run(jobPayEmployeeCalculation, jobParameters);

            int i = 0;
            while (true) {
                if (jobExecution.getStatus() == BatchStatus.STARTED
                        || jobExecution.getStatus() == BatchStatus.STARTING) {
                    if (i <= 85) {
                        setProgress(i++);
                    }
                    try {
                        Thread.sleep(sleepVariable);
                    } catch (InterruptedException e) {
                    }
                } else {
                    setProgress(100);
                    break;
                }
            }

        } catch (Exception ex) {
            LOGGER.error("Error ", ex);
        }
    }
}

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

/**
 * Given a step and configuration, return true if the step should start,
 * false if it should not, and throw an exception if the job should finish.
 * @param lastStepExecution the last step execution
 * @param jobExecution//w  w  w  .  jav a  2 s .c  o m
 * @param step
 *
 * @throws StartLimitExceededException if the start limit has been exceeded
 * for this step
 * @throws JobRestartException if the job is in an inconsistent state from
 * an earlier failure
 */
protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step)
        throws JobRestartException, StartLimitExceededException {

    BatchStatus stepStatus;
    if (lastStepExecution == null) {
        stepStatus = BatchStatus.STARTING;
    } else {
        stepStatus = lastStepExecution.getStatus();
    }

    if (stepStatus == BatchStatus.UNKNOWN) {
        throw new JobRestartException("Cannot restart step from UNKNOWN status. "
                + "The last execution ended with a failure that could not be rolled back, "
                + "so it may be dangerous to proceed. Manual intervention is probably necessary.");
    }

    if ((stepStatus == BatchStatus.COMPLETED && !step.isAllowStartIfComplete())
            || stepStatus == BatchStatus.ABANDONED) {
        // step is complete, false should be returned, indicating that the
        // step should not be started
        logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution);
        return false;
    }

    if (jobRepository.getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step
            .getStartLimit()) {
        // step start count is less than start max, return true
        return true;
    } else {
        // start max has been exceeded, throw an exception.
        throw new StartLimitExceededException("Maximum start limit exceeded for step: " + step.getName()
                + "StartMax: " + step.getStartLimit());
    }
}

From source file:org.springframework.batch.core.jsr.job.DefaultStepHandler.java

/**
 * Given a step and configuration, return true if the step should start,
 * false if it should not, and throw an exception if the job should finish.
 * @param lastStepExecution the last step execution
 * @param jobInstance/*  www .jav  a 2 s  .c  om*/
 * @param step
 *
 * @throws StartLimitExceededException if the start limit has been exceeded
 * for this step
 * @throws JobRestartException if the job is in an inconsistent state from
 * an earlier failure
 */
@Override
protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step)
        throws JobRestartException, StartLimitExceededException {
    BatchStatus stepStatus;
    String restartStep = null;
    if (lastStepExecution == null) {
        jobExecution.getExecutionContext().put("batch.startedStep", step.getName());
        stepStatus = BatchStatus.STARTING;
    } else {
        stepStatus = lastStepExecution.getStatus();

        JobExecution lastJobExecution = getLastJobExecution(jobExecution);

        if (lastJobExecution.getExecutionContext().containsKey("batch.restartStep")) {
            restartStep = lastJobExecution.getExecutionContext().getString("batch.restartStep");

            if (CollectionUtils.isEmpty(jobExecution.getStepExecutions())
                    && lastJobExecution.getStatus() == BatchStatus.STOPPED
                    && StringUtils.hasText(restartStep)) {
                if (!restartStep.equals(step.getName())
                        && !jobExecution.getExecutionContext().containsKey("batch.startedStep")) {
                    logger.info("Job was stopped and should restart at step " + restartStep
                            + ".  The current step is " + step.getName());
                    return false;
                } else {
                    // Indicates the starting point for execution evaluation per JSR-352
                    jobExecution.getExecutionContext().put("batch.startedStep", step.getName());
                }
            }
        }
    }

    if (stepStatus == BatchStatus.UNKNOWN) {
        throw new JobRestartException("Cannot restart step from UNKNOWN status. "
                + "The last execution ended with a failure that could not be rolled back, "
                + "so it may be dangerous to proceed. Manual intervention is probably necessary.");
    }

    if ((stepStatus == BatchStatus.COMPLETED && step.isAllowStartIfComplete() == false)
            || stepStatus == BatchStatus.ABANDONED) {
        // step is complete, false should be returned, indicating that the
        // step should not be started
        logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution);
        return false;
    }

    if (getJobRepository().getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step
            .getStartLimit()) {
        // step start count is less than start max, return true
        return true;
    } else {
        // start max has been exceeded, throw an exception.
        throw new StartLimitExceededException("Maximum start limit exceeded for step: " + step.getName()
                + "StartMax: " + step.getStartLimit());
    }
}

From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java

/**
 * Stops the running job execution if it is currently running.
 *
 * @param executionId the database id for the {@link JobExecution} to be stopped.
 * @throws NoSuchJobExecutionException/*ww  w . java2 s  .  co m*/
 * @throws JobExecutionNotRunningException
 */
@Override
public void stop(long executionId)
        throws NoSuchJobExecutionException, JobExecutionNotRunningException, JobSecurityException {
    org.springframework.batch.core.JobExecution jobExecution = jobExplorer.getJobExecution(executionId);
    // Indicate the execution should be stopped by setting it's status to
    // 'STOPPING'. It is assumed that
    // the step implementation will check this status at chunk boundaries.
    BatchStatus status = jobExecution.getStatus();
    if (!(status == BatchStatus.STARTED || status == BatchStatus.STARTING)) {
        throw new JobExecutionNotRunningException(
                "JobExecution must be running so that it can be stopped: " + jobExecution);
    }
    jobExecution.setStatus(BatchStatus.STOPPING);
    jobRepository.update(jobExecution);

    try {
        Job job = jobRegistry.getJob(jobExecution.getId());
        if (job instanceof StepLocator) {//can only process as StepLocator is the only way to get the step object
            //get the current stepExecution
            for (org.springframework.batch.core.StepExecution stepExecution : jobExecution
                    .getStepExecutions()) {
                if (stepExecution.getStatus().isRunning()) {
                    try {
                        //have the step execution that's running -> need to 'stop' it
                        Step step = ((StepLocator) job).getStep(stepExecution.getStepName());
                        if (step instanceof TaskletStep) {
                            Tasklet tasklet = ((TaskletStep) step).getTasklet();
                            if (tasklet instanceof StoppableTasklet) {
                                StepSynchronizationManager.register(stepExecution);
                                ((StoppableTasklet) tasklet).stop();
                                StepSynchronizationManager.release();
                            }
                        }
                    } catch (NoSuchStepException e) {
                        logger.warn("Step not found", e);
                    }
                }
            }
        }
    } catch (NoSuchJobException e) {
        logger.warn("Cannot find Job object", e);
    }
}

From source file:org.springframework.batch.core.launch.support.SimpleJobOperator.java

@Override
@Transactional// ww  w.  ja v a  2s .  co m
public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException {

    JobExecution jobExecution = findExecutionById(executionId);
    // Indicate the execution should be stopped by setting it's status to
    // 'STOPPING'. It is assumed that
    // the step implementation will check this status at chunk boundaries.
    BatchStatus status = jobExecution.getStatus();
    if (!(status == BatchStatus.STARTED || status == BatchStatus.STARTING)) {
        throw new JobExecutionNotRunningException(
                "JobExecution must be running so that it can be stopped: " + jobExecution);
    }
    jobExecution.setStatus(BatchStatus.STOPPING);
    jobRepository.update(jobExecution);

    try {
        Job job = jobRegistry.getJob(jobExecution.getJobInstance().getJobName());
        if (job instanceof StepLocator) {//can only process as StepLocator is the only way to get the step object
            //get the current stepExecution
            for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
                if (stepExecution.getStatus().isRunning()) {
                    try {
                        //have the step execution that's running -> need to 'stop' it
                        Step step = ((StepLocator) job).getStep(stepExecution.getStepName());
                        if (step instanceof TaskletStep) {
                            Tasklet tasklet = ((TaskletStep) step).getTasklet();
                            if (tasklet instanceof StoppableTasklet) {
                                StepSynchronizationManager.register(stepExecution);
                                ((StoppableTasklet) tasklet).stop();
                                StepSynchronizationManager.release();
                            }
                        }
                    } catch (NoSuchStepException e) {
                        logger.warn("Step not found", e);
                    }
                }
            }
        }
    } catch (NoSuchJobException e) {
        logger.warn("Cannot find Job object", e);
    }

    return true;
}