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

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

Introduction

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

Prototype

public void upgradeStatus(BatchStatus status) 

Source Link

Document

Upgrade the status field if the provided value is greater than the existing one.

Usage

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

@Override
public void synchronizeStatus(JobExecution jobExecution) {
    JobExecution saved = getJobExecution(jobExecution.getId());
    if (saved.getVersion().intValue() != jobExecution.getVersion().intValue()) {
        jobExecution.upgradeStatus(saved.getStatus());
        jobExecution.setVersion(saved.getVersion());
    }//from  w  w  w  .  j ava2  s.  c  om
}

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;/*from  www  .  j  a v  a2 s .  co m*/
    }
    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:com.xchanging.support.batch.admin.service.SimpleJobService.java

public JobExecution abandon(Long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {

    JobExecution jobExecution = getJobExecution(jobExecutionId);
    if (jobExecution.getStatus().isLessThan(BatchStatus.STOPPING)) {
        throw new JobExecutionAlreadyRunningException(
                "JobExecution is running or complete and therefore cannot be aborted");
    }/*from w w  w. j a va 2  s . c  om*/

    logger.info("Aborting job execution: " + jobExecution);
    jobExecution.upgradeStatus(BatchStatus.ABANDONED);
    jobExecution.setEndTime(new Date());
    jobRepository.update(jobExecution);
    return jobExecution;

}

From source file:admin.service.SimpleJobService.java

@Override
public JobExecution abandon(Long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {

    JobExecution jobExecution = getJobExecution(jobExecutionId);
    if (jobExecution.getStatus().isLessThan(BatchStatus.STOPPING)) {
        throw new JobExecutionAlreadyRunningException(
                "JobExecution is running or complete and therefore cannot be aborted");
    }//from  w ww .j  a  v a 2 s. c  om

    logger.info("Aborting job execution: " + jobExecution);
    jobExecution.upgradeStatus(BatchStatus.ABANDONED);
    jobExecution.setEndTime(new Date());
    jobRepository.update(jobExecution);
    return jobExecution;

}

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

/**
 * Interface method implementation. /* w  w  w  .  j a v a 2s.  c o m*/
 * @see org.springframework.batch.admin.service.JobService#abandon(java.lang.Long)
 */
public JobExecution abandon(Long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {
    JobExecution jobExecution = getJobExecution(jobExecutionId);
    if (jobExecution.getStatus().isLessThan(BatchStatus.STOPPING)) {
        throw new JobExecutionAlreadyRunningException(
                "JobExecution is running or complete and therefore cannot be aborted");
    }

    LOGGER.info("Aborting job execution: " + jobExecution);
    jobExecution.upgradeStatus(BatchStatus.ABANDONED);
    jobExecution.setEndTime(new Date());
    jobRepository.update(jobExecution);
    return jobExecution;
}

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);//  w  ww. jav  a 2  s . co  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.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.//  www  . ja  va 2s. c  o 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;
}

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

@Override
public JobExecution abandon(long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {
    JobExecution jobExecution = findExecutionById(jobExecutionId);

    if (jobExecution.getStatus().isLessThan(BatchStatus.STOPPING)) {
        throw new JobExecutionAlreadyRunningException(
                "JobExecution is running or complete and therefore cannot be aborted");
    }/* www .ja  v a2s. c om*/

    logger.info("Aborting job execution: " + jobExecution);
    jobExecution.upgradeStatus(BatchStatus.ABANDONED);
    jobExecution.setEndTime(new Date());
    jobRepository.update(jobExecution);

    return jobExecution;
}

From source file:org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.java

@Override
public void synchronizeStatus(JobExecution jobExecution) {
    int currentVersion = getJdbcTemplate().queryForObject(getQuery(CURRENT_VERSION_JOB_EXECUTION),
            Integer.class, jobExecution.getId());

    if (currentVersion != jobExecution.getVersion().intValue()) {
        String status = getJdbcTemplate().queryForObject(getQuery(GET_STATUS), String.class,
                jobExecution.getId());/* www.  j  a  va2 s .  com*/
        jobExecution.upgradeStatus(BatchStatus.valueOf(status));
        jobExecution.setVersion(currentVersion);
    }
}

From source file:org.springframework.cloud.dataflow.server.batch.SimpleJobService.java

@Override
public JobExecution abandon(Long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException {

    JobExecution jobExecution = getJobExecution(jobExecutionId);
    if (jobExecution.getStatus().isLessThan(BatchStatus.STOPPING)) {
        throw new JobExecutionAlreadyRunningException(
                "JobExecution is running or complete and therefore cannot be aborted");
    }//ww  w .  j a va2s. c om

    logger.info("Aborting job execution: " + jobExecution);

    Collection<String> jsrJobNames = getJsrJobNames();

    JobInstance jobInstance = jobExecution.getJobInstance();
    if (jsrJobOperator != null && jsrJobNames.contains(jobInstance.getJobName())) {
        jsrJobOperator.abandon(jobExecutionId);
        jobExecution = getJobExecution(jobExecutionId);
    } else {
        jobExecution.upgradeStatus(BatchStatus.ABANDONED);
        jobExecution.setEndTime(new Date());
        jobRepository.update(jobExecution);
    }

    return jobExecution;

}