List of usage examples for org.springframework.batch.core JobExecution setStatus
public void setStatus(BatchStatus status)
From source file:org.springframework.batch.core.job.SimpleStepHandler.java
@Override public StepExecution handleStep(Step step, JobExecution execution) throws JobInterruptedException, JobRestartException, StartLimitExceededException { if (execution.isStopping()) { throw new JobInterruptedException("JobExecution interrupted."); }//from ww w . j a v a 2s.c o m JobInstance jobInstance = execution.getJobInstance(); StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobInstance, step.getName()); if (stepExecutionPartOfExistingJobExecution(execution, lastStepExecution)) { // If the last execution of this step was in the same job, it's // probably intentional so we want to run it again... logger.info(String.format( "Duplicate step [%s] detected in execution of job=[%s]. " + "If either step fails, both will be executed again on restart.", step.getName(), jobInstance.getJobName())); lastStepExecution = null; } StepExecution currentStepExecution = lastStepExecution; if (shouldStart(lastStepExecution, execution, step)) { currentStepExecution = execution.createStepExecution(step.getName()); boolean isRestart = (lastStepExecution != null && !lastStepExecution.getStatus().equals(BatchStatus.COMPLETED)); if (isRestart) { currentStepExecution.setExecutionContext(lastStepExecution.getExecutionContext()); if (lastStepExecution.getExecutionContext().containsKey("batch.executed")) { currentStepExecution.getExecutionContext().remove("batch.executed"); } } else { currentStepExecution.setExecutionContext(new ExecutionContext(executionContext)); } jobRepository.add(currentStepExecution); logger.info("Executing step: [" + step.getName() + "]"); try { step.execute(currentStepExecution); currentStepExecution.getExecutionContext().put("batch.executed", true); } catch (JobInterruptedException e) { // Ensure that the job gets the message that it is stopping // and can pass it on to other steps that are executing // concurrently. execution.setStatus(BatchStatus.STOPPING); throw e; } jobRepository.updateExecutionContext(execution); if (currentStepExecution.getStatus() == BatchStatus.STOPPING || currentStepExecution.getStatus() == BatchStatus.STOPPED) { // Ensure that the job gets the message that it is stopping execution.setStatus(BatchStatus.STOPPING); throw new JobInterruptedException("Job interrupted by step execution"); } } return currentStepExecution; }
From source file:org.springframework.batch.core.launch.support.CommandLineJobRunner.java
@SuppressWarnings("resource") int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; try {/* w w w .j a v a 2 s . c o m*/ try { context = new AnnotationConfigApplicationContext(Class.forName(jobPath)); } catch (ClassNotFoundException cnfe) { 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."); 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."); } String jobName = jobIdentifier; 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)."); 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()); } 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()); } 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.getJobParameters(); jobName = jobExecution.getJobInstance().getJobName(); } Job job = null; if (jobLocator != null) { try { job = jobLocator.getJob(jobName); } catch (NoSuchJobException e) { } } if (job == null) { job = (Job) context.getBean(jobName); } 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); } JobExecution jobExecution = launcher.run(job, jobParameters); return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode()); } catch (Throwable e) { String message = "Job Terminated in error: " + e.getMessage(); logger.error(message, e); CommandLineJobRunner.message = message; return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()); } finally { if (context != null) { context.close(); } } }
From source file:org.springframework.batch.core.launch.support.SimpleJobOperator.java
@Override @Transactional/* www. j ava 2 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.SystemCommandTaskletIntegrationTests.java
@Test public void testStopped() throws Exception { initializeTasklet();/* ww w . jav a 2 s . c o m*/ tasklet.setJobExplorer(jobExplorer); tasklet.afterPropertiesSet(); tasklet.beforeStep(stepExecution); JobExecution stoppedJobExecution = new JobExecution(stepExecution.getJobExecution()); stoppedJobExecution.setStatus(BatchStatus.STOPPING); when(jobExplorer.getJobExecution(1L)).thenReturn(stepExecution.getJobExecution(), stepExecution.getJobExecution(), stoppedJobExecution); String command = System.getProperty("os.name").toLowerCase().contains("win") ? "ping 1.1.1.1 -n 1 -w 5000" : "sleep 15"; tasklet.setCommand(command); tasklet.setTerminationCheckInterval(10); tasklet.afterPropertiesSet(); StepContribution contribution = stepExecution.createStepContribution(); StepContext stepContext = new StepContext(stepExecution); ChunkContext chunkContext = new ChunkContext(stepContext); tasklet.execute(contribution, chunkContext); assertEquals(contribution.getExitStatus().getExitCode(), ExitStatus.STOPPED.getExitCode()); }
From source file:org.springframework.batch.core.test.repository.JdbcJobRepositoryTests.java
@Test public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { job = new JobSupport("test-job"); job.setRestartable(true);//from ww w .java2 s . c o m job.setName("spam"); JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); cacheJobIds(execution); execution.setEndTime(new Timestamp(System.currentTimeMillis())); repository.update(execution); execution.setStatus(BatchStatus.FAILED); int before = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE", Integer.class); assertEquals(1, before); long t0 = System.currentTimeMillis(); try { doConcurrentStart(); fail("Expected JobExecutionAlreadyRunningException"); } catch (JobExecutionAlreadyRunningException e) { // expected } long t1 = System.currentTimeMillis(); int after = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE", Integer.class); assertNotNull(execution.getId()); assertEquals(before, after); logger.info("Duration: " + (t1 - t0) + " - the second transaction did not block if this number is less than about 1000."); }
From source file:org.springframework.batch.sample.support.JdbcJobRepositoryTests.java
@Test public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { job = new JobSupport("test-job"); job.setRestartable(true);/*from w ww.ja va 2 s . c o m*/ job.setName("spam"); JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); cacheJobIds(execution); execution.setEndTime(new Timestamp(System.currentTimeMillis())); repository.update(execution); execution.setStatus(BatchStatus.FAILED); int before = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(1, before); long t0 = System.currentTimeMillis(); try { doConcurrentStart(); fail("Expected JobExecutionAlreadyRunningException"); } catch (JobExecutionAlreadyRunningException e) { // expected } long t1 = System.currentTimeMillis(); int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertNotNull(execution.getId()); assertEquals(before, after); logger.info("Duration: " + (t1 - t0) + " - the second transaction did not block if this number is less than about 1000."); }