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

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

Introduction

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

Prototype

public Long getId() 

Source Link

Usage

From source file:org.obiba.onyx.core.service.impl.DefaultAppointmentManagementServiceImpl.java

public List<AppointmentUpdateLog> getLogListForDate(Date date) {
    List<AppointmentUpdateLog> logList = new ArrayList<AppointmentUpdateLog>();
    List<JobInstance> jobsList = jobExplorer.getJobInstances(job.getName(), 0, 10);

    JobExecution jobExecution = null;

    for (JobInstance jobInstance : jobsList) {
        if (jobInstance.getJobParameters().getDate("date").toString().equals(date.toString())) {
            jobExecution = jobExplorer.getJobExecutions(jobInstance).get(0);
            break;
        }/*from   ww  w .  ja v a  2 s  .c  o m*/
    }

    if (jobExecution == null)
        return null;

    for (StepExecution stepExec : jobExecution.getStepExecutions()) {
        StepExecution stepExecution = jobExplorer.getStepExecution(jobExecution.getId(), stepExec.getId());
        if (stepExecution.getExecutionContext().get("logList") != null) {
            logList.addAll((List<AppointmentUpdateLog>) (stepExecution.getExecutionContext().get("logList")));
        }
    }

    return logList;
}

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

/**
 * Check all the active executions and see if they are still actually
 * running. Remove the ones that have completed.
 *//*from  ww  w .j  a v a  2 s.com*/
@Scheduled(fixedDelay = 60000)
public void removeInactiveExecutions() {
    for (Iterator<JobExecution> iterator = activeExecutions.iterator(); iterator.hasNext();) {
        JobExecution jobExecution = iterator.next();
        try {
            jobExecution = getJobExecution(jobExecution.getId());
        } catch (NoSuchJobExecutionException e) {
            LOGGER.error("Unexpected exception loading JobExecution", e);
        }
        if (!jobExecution.isRunning()) {
            iterator.remove();
        }
    }
}

From source file:com.iisigroup.cap.batch.handler.BatchHandler.java

/**
 * /*  ww  w  . ja  v a 2s  . c  o  m*/
 * 
 * @param request
 *            request
 * @return IResult
 */
public Result jobExecute(Request request) {
    String params = request.get("jobParams");
    JobParameters jobParameters = jobParametersExtractor.fromString(params);

    BatchJob batchJob = batchSrv.findJobById(request.get("jobId"));
    if (batchJob != null) {
        String jobName = batchJob.getJobId();
        try {
            JobExecution jobExecution = jobService.launch(jobName, jobParameters);
            // new JobExecutionInfo(jobExecution, TimeZone.getDefault());
            batchSrv.updateExecution(jobExecution.getId(), CapSecurityContext.getUserId());
        } catch (NoSuchJobException e) {
            throw new CapMessageException("msg.job.noSuchJob", getClass());
        } catch (JobExecutionAlreadyRunningException e) {
            throw new CapMessageException("msg.job.alreadyRunning", getClass());
        } catch (JobRestartException e) {
            throw new CapMessageException("msg.job.canNotRestart", getClass());
        } catch (JobInstanceAlreadyCompleteException e) {
            throw new CapMessageException("msg.job.alreadyComplete", getClass());
        } catch (JobParametersInvalidException e) {
            throw new CapMessageException("msg.job.parametersInvalid", getClass());
        }
    }
    return new AjaxFormResult();
}

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

/**
 * Interface method implementation.Stops all the active jobs and wait for them (up to a time out) to finish
 * processing./*from   w w  w.j  a  v a 2s .c om*/
 * @see org.springframework.beans.factory.DisposableBean#destroy()
 */
public void destroy() throws Exception {
    Exception firstException = null;
    for (JobExecution jobExecution : activeExecutions) {
        try {
            if (jobExecution.isRunning()) {
                stop(jobExecution.getId());
            }
        } catch (JobExecutionNotRunningException e) {
            LOGGER.info("JobExecution is not running so it cannot be stopped");
        } catch (Exception e) {
            LOGGER.error("Unexpected exception stopping JobExecution", e);
            if (firstException == null) {
                firstException = e;
            }
        }
    }
    int count = 0;
    int maxCount = (shutdownTimeout + 1000) / 1000;
    while (!activeExecutions.isEmpty() && ++count < maxCount) {
        LOGGER.error("Waiting for " + activeExecutions.size() + " active executions to complete");
        removeInactiveExecutions();
        Thread.sleep(1000L);
    }
    if (firstException != null) {
        throw firstException;
    }
}

From source file:uk.ac.kcl.scheduling.SingleJobLauncher.java

public void launchJob() {
    JobExecution lastJobExecution = getLastJobExecution();
    try {/*  w  w w.  j  a v a2  s . c o m*/
        if (lastJobExecution != null) {
            BatchStatus lastJobStatus = lastJobExecution.getStatus();
            switch (lastJobStatus) {
            case COMPLETED:
                LOG.info("Last job execution was successful");
                startNextInstance();
                break;
            case STARTED:
            case STARTING:
            case STOPPING:
                LOG.info("Job is already running. Repository in unknown state."
                        + " Attempting to repair and restart from last successful job");
                abandonAllJobsStartedAfterLastSuccessfulJob();
                startNextInstance();
                break;
            case FAILED:
                LOG.info("Last job failed. Attempting restart");
                startNextInstance();
                break;
            case ABANDONED:
                LOG.info("Last job was abandoned. Attempting start from last successful job");
                abandonAllJobsStartedAfterLastSuccessfulJob();
                startNextInstance();
                break;
            case STOPPED:
                LOG.info("Last job was stopped. Attempting restart");
                startNextInstance();
                break;
            case UNKNOWN:
                LOG.info(
                        "Last job has unknown status. Marking as abandoned and attempting restart from last successful job");
                abandonAllJobsStartedAfterLastSuccessfulJob();
                startNextInstance();
                break;
            default:
                LOG.error("Should be unreachable");
                break;
            }
        } else {
            LOG.info("No previous completed jobs found");
            startNextInstance();
        }
    } catch (JobInstanceAlreadyCompleteException | JobExecutionAlreadyRunningException
            | JobParametersInvalidException e) {
        LOG.error("Cannot start job", e);
    } catch (JobRestartException e) {
        LOG.error("Cannot restart job. Attempting start from last successful job", e);
        try {
            jobOperator.abandon(lastJobExecution.getId());
            startNextInstance();
        } catch (NoSuchJobExecutionException | JobExecutionAlreadyRunningException | NoSuchJobException
                | JobInstanceAlreadyCompleteException | JobRestartException | JobParametersNotFoundException
                | JobParametersInvalidException e1) {
            throw new RuntimeException("Cannot start next instance", e1);
        }
    } catch (Exception e) {
        LOG.error("Cannot start job", e);
    }
}

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);//www  .j  a  v  a  2  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.explore.support.SimpleJobExplorerIntegrationTests.java

@Test
public void testGetStepExecution() throws JobExecutionAlreadyRunningException, JobRestartException,
        JobInstanceAlreadyCompleteException, JobInterruptedException, UnexpectedJobExecutionException {

    // Prepare the jobRepository for the test
    JobExecution jobExecution = jobRepository.createJobExecution("myJob", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution("flowStep");
    jobRepository.add(stepExecution);/*from w w w  .  j a v  a  2s. c om*/

    // Executed on the remote end in remote partitioning use case
    StepExecution jobExplorerStepExecution = jobExplorer.getStepExecution(jobExecution.getId(),
            stepExecution.getId());
    flowStep.execute(jobExplorerStepExecution);

    assertEquals(BatchStatus.COMPLETED, jobExplorerStepExecution.getStatus());
}

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

/**
 * Detect whether a step execution belongs to this job execution.
 * @param jobExecution the current job execution
 * @param stepExecution an existing step execution
 * @return true if the {@link org.springframework.batch.core.StepExecution} is part of the {@link org.springframework.batch.core.JobExecution}
 *//*  www .  jav a  2s  . co m*/
private boolean stepExecutionPartOfExistingJobExecution(JobExecution jobExecution,
        StepExecution stepExecution) {
    return stepExecution != null && stepExecution.getJobExecutionId() != null
            && stepExecution.getJobExecutionId().equals(jobExecution.getId());
}

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

/**
 * Since all JSR-352 jobs are run asynchronously, {@link JobRepository#getLastJobExecution(String, org.springframework.batch.core.JobParameters)}
 * could return the currently running {@link JobExecution}.  To get around this, we use the {@link JobExplorer}
 * to get a list of the executions and get the most recent one that is <em>not</em> the currently running
 * {@link JobExecution}./*from   w  ww  .j  a v  a 2s. c om*/
 *
 * @param jobExecution
 * @return the last executed JobExecution.
 */
private JobExecution getLastJobExecution(JobExecution jobExecution) {
    List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobExecution.getJobInstance());
    JobExecution lastJobExecution = null;

    for (JobExecution curJobExecution : jobExecutions) {
        if (lastJobExecution == null
                && curJobExecution.getId().longValue() != jobExecution.getId().longValue()) {
            lastJobExecution = curJobExecution;
        } else if (curJobExecution.getId().longValue() != jobExecution.getId().longValue()
                && (lastJobExecution == null
                        || curJobExecution.getId().longValue() > lastJobExecution.getId().longValue())) {
            lastJobExecution = curJobExecution;
        }
    }
    return lastJobExecution;
}

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

@Override
public List<Long> getExecutions(long instanceId) throws NoSuchJobInstanceException {
    JobInstance jobInstance = jobExplorer.getJobInstance(instanceId);
    if (jobInstance == null) {
        throw new NoSuchJobInstanceException(String.format("No job instance with id=%d", instanceId));
    }//from   ww w .  ja va 2 s  .  c o m
    List<Long> list = new ArrayList<Long>();
    for (JobExecution jobExecution : jobExplorer.getJobExecutions(jobInstance)) {
        list.add(jobExecution.getId());
    }
    return list;
}