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

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

Introduction

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

Prototype

BatchStatus STARTED

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

Click Source Link

Usage

From source file:io.spring.batch.integration.ExecutionToTweetTransformer.java

@Transformer(inputChannel = "jobRequests", outputChannel = "statusTweets")
public TweetData transform(JobExecution execution) {
    DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SS");
    StringBuilder builder = new StringBuilder();

    builder.append(execution.getJobInstance().getJobName());

    BatchStatus evaluatedStatus = endingBatchStatus(execution);
    if (evaluatedStatus == BatchStatus.COMPLETED || evaluatedStatus.compareTo(BatchStatus.STARTED) > 0) {
        builder.append(" has completed with a status of " + execution.getStatus().name() + " at "
                + formatter.format(new Date()));
    } else {/*from ww w.j ava 2 s . c o m*/
        builder.append(" has started at " + formatter.format(new Date()));
    }

    return new TweetData(builder.toString());
}

From source file:com.create.batch.TicketJobExecutionListenerTest.java

@Test
public void testAfterJobNotCompleted() throws Exception {
    // given/*from  w w  w .  j a  v  a 2s .c om*/
    final JobExecution jobExecution = mock(JobExecution.class);
    when(jobExecution.getStatus()).thenReturn(BatchStatus.STARTED);

    // when
    listener.afterJob(jobExecution);

    // then
    verifyNoMoreInteractions(metricProvider);
}

From source file:org.springframework.batch.admin.domain.JobExecutionInfoResource.java

public JobExecutionInfoResource(JobExecution jobExecution, TimeZone timeZone) {

    if (timeZone != null) {
        this.timeZone = timeZone;
    } else {//from  w w  w .j  ava  2s .com
        this.timeZone = TimeZone.getTimeZone("UTC");
    }

    this.executionId = jobExecution.getId();
    this.jobId = jobExecution.getJobId();
    this.stepExecutionCount = jobExecution.getStepExecutions().size();
    this.jobParameters = jobExecution.getJobParameters();
    this.status = jobExecution.getStatus();
    this.exitStatus = jobExecution.getExitStatus();
    this.jobConfigurationName = jobExecution.getJobConfigurationName();
    this.failureExceptions = jobExecution.getFailureExceptions();
    Map<String, Object> executionContextEntires = new HashMap<String, Object>(
            jobExecution.getExecutionContext().size());

    for (Map.Entry<String, Object> stringObjectEntry : jobExecution.getExecutionContext().entrySet()) {
        executionContextEntires.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
    }

    this.executionContext = executionContextEntires;

    this.version = jobExecution.getVersion();

    JobInstance jobInstance = jobExecution.getJobInstance();
    if (jobInstance != null) {
        this.jobName = jobInstance.getJobName();
        BatchStatus status = jobExecution.getStatus();
        this.restartable = status.isGreaterThan(BatchStatus.STOPPING)
                && status.isLessThan(BatchStatus.ABANDONED);
        this.abandonable = status.isGreaterThan(BatchStatus.STARTED) && status != BatchStatus.ABANDONED;
        this.stoppable = status.isLessThan(BatchStatus.STOPPING) && status != BatchStatus.COMPLETED;
    } else {
        this.jobName = "?";
    }

    this.dateFormat = this.dateFormat.withZone(DateTimeZone.forTimeZone(timeZone));

    this.createDate = dateFormat.print(jobExecution.getCreateTime().getTime());
    this.lastUpdated = dateFormat.print(jobExecution.getLastUpdated().getTime());

    if (jobExecution.getStartTime() != null) {
        this.startTime = dateFormat.print(jobExecution.getStartTime().getTime());
        this.endTime = dateFormat.print(jobExecution.getEndTime().getTime());
    }
}

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 {// w  w  w .j  a  va 2 s  . c  om

            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  ww  . ja  v a  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:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 *  JobExecution ?? ./* ww  w . j  a  v  a 2s  . c o  m*/
 * 
 * @param jobIdentifier
 * @return List<JobExecution> :  JobExecution ?
 */
private List<JobExecution> getStoppedJobExecutions(String jobIdentifier) {
    List<JobExecution> jobExecutions = getJobExecutionsWithStatusGreaterThan(jobIdentifier,
            BatchStatus.STARTED);
    if (jobExecutions.isEmpty()) {
        return null;
    }
    List<JobExecution> result = new ArrayList<JobExecution>();
    for (JobExecution jobExecution : jobExecutions) {
        if (jobExecution.getStatus() != BatchStatus.ABANDONED) {
            result.add(jobExecution);
        }
    }
    return result.isEmpty() ? null : result;
}

From source file:org.geoserver.backuprestore.Backup.java

/**
 * Stop a running Backup/Restore Execution
 * /*from   w w  w . j a v  a2 s  . com*/
 * @param executionId
 * @return
 * @throws NoSuchJobExecutionException
 * @throws JobExecutionNotRunningException
 */
public void stopExecution(Long executionId)
        throws NoSuchJobExecutionException, JobExecutionNotRunningException {
    LOGGER.info("Stopping execution id [" + executionId + "]");

    JobExecution jobExecution = null;
    try {
        if (this.backupExecutions.get(executionId) != null) {
            jobExecution = this.backupExecutions.get(executionId).getDelegate();
        } else if (this.restoreExecutions.get(executionId) != null) {
            jobExecution = this.restoreExecutions.get(executionId).getDelegate();
        }

        jobOperator.stop(executionId);
    } finally {
        if (jobExecution != null) {
            final BatchStatus status = jobExecution.getStatus();

            if (!status.isGreaterThan(BatchStatus.STARTED)) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobExecution.setEndTime(new Date());
                jobRepository.update(jobExecution);
            }
        }

        // Release locks on GeoServer Configuration:
        try {
            List<BackupRestoreCallback> callbacks = GeoServerExtensions.extensions(BackupRestoreCallback.class);
            for (BackupRestoreCallback callback : callbacks) {
                callback.onEndRequest();
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Could not unlock GeoServer Catalog Configuration!", e);
        }
    }
}

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

/**
 * Run the specified job, handling all listener and repository calls, and
 * delegating the actual processing to {@link #doExecute(JobExecution)}.
 *
 * @see Job#execute(JobExecution)/*from   ww w  . j  av a 2  s  . c o  m*/
 * @throws StartLimitExceededException
 *             if start limit of one of the steps was exceeded
 */
@Override
public final void execute(JobExecution execution) {

    if (logger.isDebugEnabled()) {
        logger.debug("Job execution starting: " + execution);
    }

    JobSynchronizationManager.register(execution);

    try {

        jobParametersValidator.validate(execution.getJobParameters());

        if (execution.getStatus() != BatchStatus.STOPPING) {

            execution.setStartTime(new Date());
            updateStatus(execution, BatchStatus.STARTED);

            listener.beforeJob(execution);

            try {
                doExecute(execution);
                if (logger.isDebugEnabled()) {
                    logger.debug("Job execution complete: " + execution);
                }
            } catch (RepeatException e) {
                throw e.getCause();
            }
        } else {

            // The job was already stopped before we even got this far. Deal
            // with it in the same way as any other interruption.
            execution.setStatus(BatchStatus.STOPPED);
            execution.setExitStatus(ExitStatus.COMPLETED);
            if (logger.isDebugEnabled()) {
                logger.debug("Job execution was stopped: " + execution);
            }

        }

    } catch (JobInterruptedException e) {
        logger.info("Encountered interruption executing job: " + e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug("Full exception", e);
        }
        execution.setExitStatus(getDefaultExitStatusForFailure(e, execution));
        execution.setStatus(BatchStatus.max(BatchStatus.STOPPED, e.getStatus()));
        execution.addFailureException(e);
    } catch (Throwable t) {
        logger.error("Encountered fatal error executing job", t);
        execution.setExitStatus(getDefaultExitStatusForFailure(t, execution));
        execution.setStatus(BatchStatus.FAILED);
        execution.addFailureException(t);
    } finally {
        try {
            if (execution.getStatus().isLessThanOrEqualTo(BatchStatus.STOPPED)
                    && execution.getStepExecutions().isEmpty()) {
                ExitStatus exitStatus = execution.getExitStatus();
                ExitStatus newExitStatus = ExitStatus.NOOP
                        .addExitDescription("All steps already completed or no steps configured for this job.");
                execution.setExitStatus(exitStatus.and(newExitStatus));
            }

            execution.setEndTime(new Date());

            try {
                listener.afterJob(execution);
            } catch (Exception e) {
                logger.error("Exception encountered in afterStep callback", e);
            }

            jobRepository.update(execution);
        } finally {
            JobSynchronizationManager.release();
        }

    }

}

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//w w  w  . j av a  2  s  .  c o 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.CommandLineJobRunner.java

private List<JobExecution> getStoppedJobExecutions(String jobIdentifier) {
    List<JobExecution> jobExecutions = getJobExecutionsWithStatusGreaterThan(jobIdentifier,
            BatchStatus.STARTED);
    if (jobExecutions.isEmpty()) {
        return null;
    }//  www.j  a va  2 s  . c o  m
    List<JobExecution> result = new ArrayList<JobExecution>();
    for (JobExecution jobExecution : jobExecutions) {
        if (jobExecution.getStatus() != BatchStatus.ABANDONED) {
            result.add(jobExecution);
        }
    }
    return result.isEmpty() ? null : result;
}