Example usage for org.springframework.batch.core JobExecution setStatus

List of usage examples for org.springframework.batch.core JobExecution setStatus

Introduction

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

Prototype

public void setStatus(BatchStatus status) 

Source Link

Document

Set the value of the status field.

Usage

From source file:org.trpr.platform.batch.impl.spring.admin.repository.MapJobExecutionDao.java

/**
 * Returns a copy of {@link JobExecution}, by adding new Objects for every field(no references are passed)
 * /*from w w w.j a v a  2 s . c  o  m*/
 * @param original JobExecution to be copied
 * @return JobExecution copy
 */
private static JobExecution copy(JobExecution original) {
    JobInstance jobInstance = original.getJobInstance();
    JobExecution copy;
    if (jobInstance == null) {
        copy = new JobExecution(original.getId());
    }
    copy = new JobExecution(jobInstance, original.getId());
    if (original.getStartTime() != null) {
        copy.setStartTime((Date) original.getStartTime().clone());
    }
    if (original.getEndTime() != null) {
        copy.setEndTime((Date) original.getEndTime().clone());
    }
    if (original.getStatus() != null) {
        copy.setStatus(BatchStatus.valueOf(original.getStatus().name()));
    }
    if (original.getExitStatus() != null) {
        copy.setExitStatus(new ExitStatus(original.getExitStatus().getExitCode(),
                original.getExitStatus().getExitDescription()));
    }
    if (original.getCreateTime() != null) {
        copy.setCreateTime((Date) original.getCreateTime().clone());
    }
    if (original.getLastUpdated() != null) {
        copy.setLastUpdated((Date) original.getLastUpdated().clone());
    }
    copy.setVersion(original.getVersion());
    return copy;
}

From source file:com.javaetmoi.core.batch.integration.TestJobExitStatusRouter.java

@Test
public void routeToErrorChannel() {
    JobExitStatusRouter router = new JobExitStatusRouter();
    router.init();/*from  ww  w.ja v a2  s  .c  om*/
    JobExecution jobExecution = new JobExecution(1L);
    jobExecution.setExitStatus(ExitStatus.FAILED);
    jobExecution.setStatus(BatchStatus.FAILED);
    assertEquals("job-error", router.route(jobExecution));
}

From source file:com.javaetmoi.core.batch.integration.TestJobExitStatusRouter.java

@Test
public void routeToSuccessChannel() {
    JobExitStatusRouter router = new JobExitStatusRouter();
    router.init();//w w w. j a  v  a  2 s .  c  o  m
    JobExecution jobExecution = new JobExecution(1L);
    jobExecution.setExitStatus(ExitStatus.COMPLETED);
    jobExecution.setStatus(BatchStatus.COMPLETED);
    assertEquals("job-success", router.route(jobExecution));
}

From source file:fr.acxio.tools.agia.admin.StaleRunningJobsService.java

public void forceRunningJobsToFail() {
    if (logger.isInfoEnabled()) {
        logger.info("Reseting jobs...");
    }//from   w w  w .ja  va2s.c o  m

    List<String> aJobNames = jobExplorer.getJobNames();
    for (String aJobName : aJobNames) {
        Set<JobExecution> aJobExecutions = jobExplorer.findRunningJobExecutions(aJobName);
        for (JobExecution aJobExecution : aJobExecutions) {
            if (logger.isInfoEnabled()) {
                logger.info("  " + aJobName + " (" + aJobExecution.getId() + ")");
            }
            aJobExecution.setEndTime(new Date());
            aJobExecution.setStatus(BatchStatus.FAILED);
            aJobExecution.setExitStatus(ExitStatus.FAILED);
            jobRepository.update(aJobExecution);
            for (StepExecution aStepExecution : aJobExecution.getStepExecutions()) {
                if (aStepExecution.getStatus().isGreaterThan(BatchStatus.COMPLETED)) {
                    if (logger.isInfoEnabled()) {
                        logger.info("    " + aStepExecution.getStepName());
                    }
                    aStepExecution.setEndTime(new Date());
                    aStepExecution.setStatus(BatchStatus.FAILED);
                    aStepExecution.setExitStatus(ExitStatus.FAILED);
                    jobRepository.update(aStepExecution);
                }
            }
        }
    }
    if (logger.isInfoEnabled()) {
        logger.info("Done.");
    }
}

From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? .//w ww. j  av a2 s  .  c  o m
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("EgovCommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        EgovCommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java

/**
 * Batch Job? ./*  ww  w . j a  va  2  s. c  o m*/
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("CommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

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

/**
 * Stop a running Backup/Restore Execution
 * //from  www . j a va2  s  . c  om
 * @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.geoserver.backuprestore.Backup.java

/**
 * Abort a running Backup/Restore Execution
 * //  w  w w  .  j  ava2s. c  o  m
 * @param executionId
 * @throws NoSuchJobExecutionException
 * @throws JobExecutionAlreadyRunningException
 */
public void abandonExecution(Long executionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {
    LOGGER.info("Aborting 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.abandon(executionId);
    } finally {
        if (jobExecution != null) {
            jobExecution.setStatus(BatchStatus.ABANDONED);
            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)/*ww  w  .j  av a2 s.com*/
 * @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.job.AbstractJob.java

private void updateStatus(JobExecution jobExecution, BatchStatus status) {
    jobExecution.setStatus(status);
    jobRepository.update(jobExecution);
}