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

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

Introduction

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

Prototype

public void setExitStatus(ExitStatus exitStatus) 

Source Link

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  . ja  va2s  .  c  om*/
 * @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();/*  w w w.j  a  v a  2 s  .  c  o  m*/
    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();/*www.ja v a2s  . 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  ww.  j a  va2s.c om

    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:com.rsone.util.JobLauncherSynchronizer.java

@AfterReturning(value = "execution(* org.springframework.batch..JobRepository+.createJobExecution(..)) && args(jobName,..)", returning = "jobExecution")
public void checkJobDuringLaunch(String jobName, JobExecution jobExecution)
        throws JobExecutionAlreadyRunningException {
    logger.debug("Re-checking for synchronization on JobExecution: " + jobExecution);
    if (!jobNames.contains(jobName)) {
        logger.debug("Not re-checking for synchronization of Job: " + jobName);
        return;//  w ww. j  a  va 2s.c  om
    }
    Set<JobExecution> running = jobExplorer.findRunningJobExecutions(jobName);
    if (running.size() > 1) {
        jobExecution.setEndTime(new Date());
        jobExecution.upgradeStatus(BatchStatus.ABANDONED);
        jobExecution.setExitStatus(jobExecution.getExitStatus().and(ExitStatus.NOOP)
                .addExitDescription("Not executed because another execution was detected for the same Job."));
        jobRepository.update(jobExecution);
        throw new JobExecutionAlreadyRunningException("An instance of this job is already active: " + jobName);
    }
}

From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java

@Override
public long start(String jobName, Properties params) throws JobStartException, JobSecurityException {
    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params);
    batchContext.setValidating(false);//from  ww  w .j  a  va2 s  .c o  m

    Resource batchXml = new ClassPathResource("/META-INF/batch.xml");
    String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml";
    Resource jobXml = new ClassPathResource(jobConfigurationLocation);

    if (batchXml.exists()) {
        batchContext.load(batchXml);
    }

    if (jobXml.exists()) {
        batchContext.load(jobXml);
    }

    AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
            .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean")
            .getBeanDefinition();
    beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
    batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition);

    batchContext.setParent(parentContext);

    try {
        batchContext.refresh();
    } catch (BeanCreationException e) {
        throw new JobStartException(e);
    }

    Assert.notNull(jobName, "The job name must not be null.");

    final org.springframework.batch.core.JobExecution jobExecution;

    try {
        JobParameters jobParameters = jobParametersConverter.getJobParameters(params);
        String[] jobNames = batchContext.getBeanNamesForType(Job.class);

        if (jobNames == null || jobNames.length <= 0) {
            throw new BatchRuntimeException("No Job defined in current context");
        }

        org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0],
                jobParameters);
        jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation);
    } catch (Exception e) {
        throw new JobStartException(e);
    }

    try {
        final Semaphore semaphore = new Semaphore(1);
        final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>());
        semaphore.acquire();

        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                JsrJobContextFactoryBean factoryBean = null;
                try {
                    factoryBean = (JsrJobContextFactoryBean) batchContext
                            .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME);
                    factoryBean.setJobExecution(jobExecution);
                    final AbstractJob job = batchContext.getBean(AbstractJob.class);
                    addListenerToJobService.addListenerToJob(job);
                    semaphore.release();
                    // Initialization of the JobExecution for job level dependencies
                    jobRegistry.register(job, jobExecution);
                    job.execute(jobExecution);
                    jobRegistry.remove(jobExecution);
                } catch (Exception e) {
                    exceptionHolder.add(e);
                } finally {
                    if (factoryBean != null) {
                        factoryBean.close();
                    }

                    batchContext.close();

                    if (semaphore.availablePermits() == 0) {
                        semaphore.release();
                    }
                }
            }
        });

        semaphore.acquire();
        if (exceptionHolder.size() > 0) {
            semaphore.release();
            throw new JobStartException(exceptionHolder.get(0));
        }
    } catch (Exception e) {
        if (jobRegistry.exists(jobExecution.getId())) {
            jobRegistry.remove(jobExecution);
        }
        jobExecution.upgradeStatus(BatchStatus.FAILED);
        if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
            jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
        }
        jobRepository.update(jobExecution);

        if (batchContext.isActive()) {
            batchContext.close();
        }

        throw new JobStartException(e);
    }
    return jobExecution.getId();
}

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   w  w  w .ja  v a  2s .co 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.launch.support.SimpleJobLauncher.java

/**
 * Run the provided job with the given {@link JobParameters}. The
 * {@link JobParameters} will be used to determine if this is an execution
 * of an existing job instance, or if a new one should be created.
 *
 * @param job the job to be run.//from www .j a v  a  2 s. co  m
 * @param jobParameters the {@link JobParameters} for this particular
 * execution.
 * @return JobExecutionAlreadyRunningException if the JobInstance already
 * exists and has an execution already running.
 * @throws JobRestartException if the execution would be a re-start, but a
 * re-start is either not allowed or not needed.
 * @throws JobInstanceAlreadyCompleteException if this instance has already
 * completed successfully
 * @throws JobParametersInvalidException
 */
@Override
public JobExecution run(final Job job, final JobParameters jobParameters)
        throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
        JobParametersInvalidException {

    Assert.notNull(job, "The Job must not be null.");
    Assert.notNull(jobParameters, "The JobParameters must not be null.");

    final JobExecution jobExecution;
    JobExecution lastExecution = jobRepository.getLastJobExecution(job.getName(), jobParameters);
    if (lastExecution != null) {
        if (!job.isRestartable()) {
            throw new JobRestartException("JobInstance already exists and is not restartable");
        }
        /*
         * validate here if it has stepExecutions that are UNKNOWN, STARTING, STARTED and STOPPING
         * retrieve the previous execution and check
         */
        for (StepExecution execution : lastExecution.getStepExecutions()) {
            BatchStatus status = execution.getStatus();
            if (status.isRunning() || status == BatchStatus.STOPPING) {
                throw new JobExecutionAlreadyRunningException(
                        "A job execution for this job is already running: " + lastExecution);
            } else if (status == BatchStatus.UNKNOWN) {
                throw new JobRestartException("Cannot restart step [" + execution.getStepName()
                        + "] 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.");
            }
        }
    }

    // Check the validity of the parameters before doing creating anything
    // in the repository...
    job.getJobParametersValidator().validate(jobParameters);

    /*
     * There is a very small probability that a non-restartable job can be
     * restarted, but only if another process or thread manages to launch
     * <i>and</i> fail a job execution for this instance between the last
     * assertion and the next method returning successfully.
     */
    jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters);

    try {
        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    logger.info("Job: [" + job + "] launched with the following parameters: [" + jobParameters
                            + "]");
                    job.execute(jobExecution);
                    logger.info("Job: [" + job + "] completed with the following parameters: [" + jobParameters
                            + "] and the following status: [" + jobExecution.getStatus() + "]");
                } catch (Throwable t) {
                    logger.info("Job: [" + job
                            + "] failed unexpectedly and fatally with the following parameters: ["
                            + jobParameters + "]", t);
                    rethrow(t);
                }
            }

            private void rethrow(Throwable t) {
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                } else if (t instanceof Error) {
                    throw (Error) t;
                }
                throw new IllegalStateException(t);
            }
        });
    } catch (TaskRejectedException e) {
        jobExecution.upgradeStatus(BatchStatus.FAILED);
        if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
            jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
        }
        jobRepository.update(jobExecution);
    }

    return jobExecution;
}