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

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

Introduction

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

Prototype

public JobInstance getJobInstance() 

Source Link

Usage

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

@Override
public Long restart(long executionId) throws JobInstanceAlreadyCompleteException, NoSuchJobExecutionException,
        NoSuchJobException, JobRestartException, JobParametersInvalidException {

    logger.info("Checking status of job execution with id=" + executionId);

    JobExecution jobExecution = findExecutionById(executionId);

    String jobName = jobExecution.getJobInstance().getJobName();
    Job job = jobRegistry.getJob(jobName);
    JobParameters parameters = jobExecution.getJobParameters();

    logger.info(String.format("Attempting to resume job with name=%s and parameters=%s", jobName, parameters));
    try {/*from  ww  w.  ja  v  a 2 s.  co  m*/
        return jobLauncher.run(job, parameters).getId();
    } catch (JobExecutionAlreadyRunningException e) {
        throw new UnexpectedJobExecutionException(
                String.format(ILLEGAL_STATE_MSG, "job execution already running", jobName, parameters), e);
    }

}

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

@Override
@Transactional//w  w w .  j  ava2  s  .c  om
public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException {

    JobExecution jobExecution = findExecutionById(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.getJobInstance().getJobName());
        if (job instanceof StepLocator) {//can only process as StepLocator is the only way to get the step object
            //get the current stepExecution
            for (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);
    }

    return true;
}

From source file:org.springframework.batch.core.step.tasklet.AsyncChunkOrientedStepIntegrationTests.java

@Test
@Ignore//from w  ww  .  j a v a  2  s.  c  o m
public void testStatus() throws Exception {

    step.setTasklet(new TestingChunkOrientedTasklet<String>(
            getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }),
            new ItemWriter<String>() {
                @Override
                public void write(List<? extends String> data) throws Exception {
                    written.addAll(data);
                }
            }, chunkOperations));

    final JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters(
            Collections.singletonMap("run.id", new JobParameter(getClass().getName() + ".1"))));
    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);

    jobRepository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    // Need a transaction so one connection is enough to get job execution and its parameters
    StepExecution lastStepExecution = new TransactionTemplate(transactionManager)
            .execute(new TransactionCallback<StepExecution>() {
                @Override
                public StepExecution doInTransaction(TransactionStatus status) {
                    return jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName());
                }
            });
    assertEquals(lastStepExecution, stepExecution);
    assertFalse(lastStepExecution == stepExecution);
}

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

@Override
public JobExecution restart(Long jobExecutionId, JobParameters params)
        throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException, JobRestartException,
        JobInstanceAlreadyCompleteException, NoSuchJobException, JobParametersInvalidException {

    JobExecution jobExecution = null;//from   ww w  . j  a  v  a  2 s  .c o m

    JobExecution target = getJobExecution(jobExecutionId);
    JobInstance lastInstance = target.getJobInstance();

    if (jobLocator.getJobNames().contains(lastInstance.getJobName())) {
        Job job = jobLocator.getJob(lastInstance.getJobName());

        jobExecution = jobLauncher.run(job, target.getJobParameters());

        if (jobExecution.isRunning()) {
            activeExecutions.add(jobExecution);
        }
    } else {
        if (jsrJobOperator != null) {
            if (params != null) {
                jobExecution = new JobExecution(jsrJobOperator.restart(jobExecutionId, params.toProperties()));
            } else {
                jobExecution = new JobExecution(jsrJobOperator.restart(jobExecutionId, new Properties()));
            }
        } else {
            throw new NoSuchJobException(
                    String.format("Can't find job associated with job execution id %s to restart",
                            String.valueOf(jobExecutionId)));
        }
    }

    return jobExecution;
}

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

@Override
public int stopAll() {
    Collection<JobExecution> result = jobExecutionDao.getRunningJobExecutions();
    Collection<String> jsrJobNames = getJsrJobNames();

    for (JobExecution jobExecution : result) {
        if (jsrJobOperator != null && jsrJobNames.contains(jobExecution.getJobInstance().getJobName())) {
            jsrJobOperator.stop(jobExecution.getId());
        } else {/*from  w  ww  . ja  v  a  2s.c o m*/
            jobExecution.stop();
            jobRepository.update(jobExecution);
        }
    }

    return result.size();
}

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

@Override
public JobExecution stop(Long jobExecutionId)
        throws NoSuchJobExecutionException, JobExecutionNotRunningException {

    JobExecution jobExecution = getJobExecution(jobExecutionId);
    if (!jobExecution.isRunning()) {
        throw new JobExecutionNotRunningException(
                "JobExecution is not running and therefore cannot be stopped");
    }/*from w w  w . j  a  va 2 s . c o m*/

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

    Collection<String> jsrJobNames = getJsrJobNames();

    if (jsrJobOperator != null && jsrJobNames.contains(jobExecution.getJobInstance().getJobName())) {
        jsrJobOperator.stop(jobExecutionId);
        jobExecution = getJobExecution(jobExecutionId);
    } else {
        jobExecution.stop();
        jobRepository.update(jobExecution);
    }
    return jobExecution;

}

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");
    }/*  w  ww .  jav  a  2  s  . c o  m*/

    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;

}

From source file:org.springframework.cloud.task.batch.handler.TaskJobLauncherCommandLineRunner.java

protected void execute(Job job, JobParameters jobParameters)
        throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
        JobParametersInvalidException, JobParametersNotFoundException {
    JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer)
            .getNextJobParameters(job).toJobParameters();
    JobExecution execution = this.jobLauncher.run(job, nextParameters);
    if (this.publisher != null) {
        this.publisher.publishEvent(new JobExecutionEvent(execution));
    }//  w ww  . j  a  va  2  s.c o  m
    if (execution.getExitStatus().getExitCode().equals(ExitStatus.FAILED.getExitCode())) {
        String message = String.format(
                "Job %s failed during " + "execution for jobId %s with jobExecutionId of %s",
                execution.getJobInstance().getJobName(), execution.getJobId(), execution.getId());
        logger.error(message);
        throw new TaskException(message);
    }
}

From source file:org.springframework.data.hadoop.admin.examples.EmailNotification.java

@Override
public void afterJob(JobExecution jobExecution) {
    logger.info("afterJob enter");
    SimpleMailMessage message = new SimpleMailMessage(templateMessage);
    message.setSubject("Spring Batch Job Status");
    message.setText("Job " + jobExecution.getJobInstance().getJobName() + " completed. Status is: "
            + jobExecution.getStatus());
    try {//from  w ww.j  a  v  a 2 s  .  c  om
        mailSender.send(message);
    } catch (Throwable t) {
        logger.error("send mail failed", t);
    }
    logger.info("sent mail");
}

From source file:uk.ac.bbsrc.tgac.miso.notification.service.IlluminaTransformer.java

public Set<String> runStatusJobToStringSet(JobExecution exec) {
    Set<String> files = new HashSet<String>();
    for (Map.Entry<String, JobParameter> params : exec.getJobInstance().getJobParameters().getParameters()
            .entrySet()) {//from www . j a va2  s .  co m
        File f = new File(params.getValue().toString());
        try {
            files.add(SubmissionUtils.transform(f));
        } catch (TransformerException e) {
            //e.printStackTrace();
            log.error("Error transforming XML: " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("Error with file IO: " + e.getMessage());
        }
    }
    return files;
}