org.springframework.batch.core.repository.JobExecutionAlreadyRunningException Java Examples

The following examples show how to use org.springframework.batch.core.repository.JobExecutionAlreadyRunningException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResponseExceptionHandler.java    From spring-batch-rest with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(BatchRuntimeException.class)
protected ResponseEntity<Object> handleBatchRuntimeException(BatchRuntimeException e, WebRequest request) {
    log.error("Request {} failed with {}", request, e);
    Throwable cause = e.getCause();
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    if (cause instanceof DuplicateJobException
            || cause instanceof JobExecutionAlreadyRunningException
            || cause instanceof JobInstanceAlreadyCompleteException)
        status = HttpStatus.CONFLICT;
    else if (cause instanceof JobParametersInvalidException
        || cause instanceof JobParametersNotFoundException)
        status = HttpStatus.BAD_REQUEST;
    else if (cause instanceof NoSuchJobException
        || cause instanceof NoSuchJobExecutionException
        || cause instanceof NoSuchJobInstanceException)
        status = HttpStatus.NOT_FOUND;

    ApiError apiError = new ApiError(status.toString(), cause.getMessage(), cause.getClass().getSimpleName(), e.getMessage());
    return handleExceptionInternal(e, apiError, new HttpHeaders(), status, request);
}
 
Example #2
Source File: SingleJobCommandLineRunner.java    From spring-boot-doma2-sample with Apache License 2.0 6 votes vote down vote up
protected BatchStatus execute(Job job, JobParameters jobParameters)
        throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
        JobParametersInvalidException, JobParametersNotFoundException {

    BatchStatus status = BatchStatus.UNKNOWN;
    val nextParameters = getNextJobParameters(job, jobParameters);

    if (nextParameters != null) {
        val execution = jobLauncher.run(job, nextParameters);

        if (publisher != null) {
            publisher.publishEvent(new JobExecutionEvent(execution));
        }

        status = execution.getStatus();
    }

    return status;
}
 
Example #3
Source File: JpaBatchTest.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void jobTest() {
	try {
		JobExecution execution = jobLauncher.run(javaJob, new JobParameters());
		assertEquals(BatchStatus.COMPLETED, execution.getStatus());
		
	} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
			| JobParametersInvalidException e) {
		e.printStackTrace();
	}

	Conference conf = conferenceDao.findById(1L);

	log.debug("conf@" + conf);
}
 
Example #4
Source File: CapitalizeNamesJobScheduler.java    From spring-batch with MIT License 5 votes vote down vote up
@Scheduled(cron = "0/10 * * * * ?")
public void runBatchJob()
    throws JobExecutionAlreadyRunningException,
    JobRestartException, JobInstanceAlreadyCompleteException,
    JobParametersInvalidException {
  LOGGER.info("start runBatchJob");

  if (enabled) {
    jobLauncher.run(capitalizeNamesJob, new JobParametersBuilder()
        .addDate("date", new Date()).toJobParameters());
  }
}
 
Example #5
Source File: JdbcBatchTest.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void jobTest() {

	JobParametersBuilder builder = new JobParametersBuilder();
	try {
		JobExecution execution = jobLauncher.run(validJob, builder.toJobParameters());
		assertEquals(BatchStatus.COMPLETED, execution.getStatus());
	} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
			| JobParametersInvalidException e) {
		e.printStackTrace();
	}

}
 
Example #6
Source File: SimpleJobService.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@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");
	}

	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;

}
 
Example #7
Source File: JobOperationsController.java    From spring-boot-starter-batch-web with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler({ JobExecutionAlreadyRunningException.class, JobExecutionAlreadyCompleteException.class,
		JobRestartException.class })
public String handleAlreadyRunningOrComplete(Exception ex) {
	LOG.warn("JobExecution already running or complete.", ex);
	return ex.getMessage();
}
 
Example #8
Source File: TaxCalculatorJobServiceTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Test
public void whenStarJobs_withGivenYearAndMonth_runJobWithParameters() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
    taxCalculatorJobService.runTaxCalculatorJob(new JobStartParams(YEAR, MONTH));

    verify(jobLauncherMock).run(any(Job.class), jobParametersArgumentCaptor.capture());

    JobParameters jobParameters = jobParametersArgumentCaptor.getValue();
    assertThat(jobParameters.getLong("year")).isEqualTo(YEAR);
    assertThat(jobParameters.getLong("month")).isEqualTo(MONTH);
}
 
Example #9
Source File: TaxCalculatorJobService.java    From batchers with Apache License 2.0 5 votes vote down vote up
protected void startJobs(long year, long month) {
    try {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("month", month)
                .addLong("year", year)
                .toJobParameters();

        LOG.info("Running job in jobservice");
        jobLauncher.run(employeeJob, jobParameters);
    } catch (JobExecutionAlreadyRunningException | JobRestartException
            | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
        LOG.error("Job running failed", e);
        //TODO shouldn't we handle this differently?
    }
}
 
Example #10
Source File: JobExecutionControllerTest.java    From spring-batch-rest with Apache License 2.0 4 votes vote down vote up
@Test
public void jobFailsWithJobExecutionAlreadyRunningException () throws Exception {
    assertJobExecutionExceptionToStatusMapping(new JobExecutionAlreadyRunningException("causeMsg"), HttpStatus.CONFLICT);
}
 
Example #11
Source File: TaskJobLauncherCommandLineRunner.java    From spring-cloud-task with Apache License 2.0 4 votes vote down vote up
protected void execute(Job job, JobParameters jobParameters)
		throws JobExecutionAlreadyRunningException, JobRestartException,
		JobInstanceAlreadyCompleteException, JobParametersInvalidException {
	String jobName = job.getName();
	JobParameters parameters = jobParameters;
	boolean jobInstanceExists = this.taskJobRepository.isJobInstanceExists(jobName,
			parameters);
	if (jobInstanceExists) {
		JobExecution lastJobExecution = this.taskJobRepository
				.getLastJobExecution(jobName, jobParameters);
		if (lastJobExecution != null && isStoppedOrFailed(lastJobExecution)
				&& job.isRestartable()) {
			// Retry a failed or stopped execution with previous parameters
			JobParameters previousParameters = lastJobExecution.getJobParameters();
			/*
			 * remove Non-identifying parameters from the previous execution's
			 * parameters since there is no way to remove them programmatically. If
			 * they are required (or need to be modified) on a restart, they need to
			 * be (re)specified.
			 */
			JobParameters previousIdentifyingParameters = removeNonIdentifying(
					previousParameters);
			// merge additional parameters with previous ones (overriding those with
			// the same key)
			parameters = merge(previousIdentifyingParameters, jobParameters);
		}
	}
	else {
		JobParametersIncrementer incrementer = job.getJobParametersIncrementer();
		if (incrementer != null) {
			JobParameters nextParameters = new JobParametersBuilder(jobParameters,
					this.taskJobExplorer).getNextJobParameters(job).toJobParameters();
			parameters = merge(nextParameters, jobParameters);
		}
	}
	JobExecution execution = this.taskJobLauncher.run(job, parameters);
	if (this.taskApplicationEventPublisher != null) {
		this.taskApplicationEventPublisher
				.publishEvent(new JobExecutionEvent(execution));
	}
	this.jobExecutionList.add(execution);
	if (execution.getStatus().equals(BatchStatus.FAILED)) {
		throwJobFailedException(Collections.singletonList(execution));
	}
}
 
Example #12
Source File: SingleJobLauncher.java    From CogStack-Pipeline with Apache License 2.0 4 votes vote down vote up
private void startNextInstance() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException,
        JobParametersInvalidException, JobRestartException, JobParametersNotFoundException, NoSuchJobException {
    jobOperator.startNextInstance(job.getName());

}
 
Example #13
Source File: AdHocSchedulerParamsTest.java    From spring-batch-rest with Apache License 2.0 4 votes vote down vote up
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void paramsAddedToScheduledJobWorks()
		throws InterruptedException, JobExecutionAlreadyRunningException, JobRestartException,
		JobInstanceAlreadyCompleteException, JobParametersInvalidException, SchedulerException {

	Job job1 = job("j1");
	Job job2 = job("j2");

	jobBuilder.registerJob(job1);
	jobBuilder.registerJob(job2);

	Map<String, Object> params = new HashMap<String, Object>();
	params.put("testParamKey", "testParamValue");

	JobParameters expectedParams = JobParamUtil.convertRawToJobParams(params);

	JobConfig job1Config = JobConfig.builder().name("j1").properties(params).build();
	JobConfig job2Config = JobConfig.builder().name("j2").properties(params).build();

	Date now = Date.from(Instant.now().plusMillis(2000));

	scheduler.start();

	when(jobLauncher.run(job1, expectedParams))
			.thenReturn(new JobExecution(new Random().nextLong(), expectedParams));

	when(jobLauncher.run(job2, expectedParams))
			.thenReturn(new JobExecution(new Random().nextLong(), expectedParams));

	scheduler.schedule(job1Config, now);
	scheduler.schedule(job2Config, TRIGGER_EVERY_SECOND);

	ArgumentCaptor<Job> jobCaptor = ArgumentCaptor.forClass(Job.class);
	ArgumentCaptor<JobParameters> jobParamCaptor = ArgumentCaptor.forClass(JobParameters.class);
	verify(jobLauncher, timeout(8000).times(2)).run(jobCaptor.capture(), jobParamCaptor.capture());

	List<JobParameters> paramsListAfterCall = jobParamCaptor.getAllValues();

	Assertions.assertEquals(paramsListAfterCall.size(), 2);

	for (JobParameters jobParams : paramsListAfterCall) {
		Assertions.assertEquals(jobParams.getString("testParamKey"), "testParamValue");
	}

	scheduler.pause();
}
 
Example #14
Source File: JobService.java    From spring-cloud-dataflow with Apache License 2.0 2 votes vote down vote up
/**
 * Mark the {@link JobExecution} as ABANDONED. If a stop signal is ignored because the
 * process died this is the best way to mark a job as finished with (as opposed to
 * STOPPED). An abandoned job execution can be restarted, but a stopping one cannot.
 * 
 * @param jobExecutionId the job execution id to abort
 * @return the {@link JobExecution} that was aborted
 * @throws NoSuchJobExecutionException thrown if job execution specified does not exist
 * @throws JobExecutionAlreadyRunningException thrown if the job is running (it should be
 *     stopped first)
 */
JobExecution abandon(Long jobExecutionId) throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException;
 
Example #15
Source File: JobService.java    From spring-cloud-dataflow with Apache License 2.0 2 votes vote down vote up
/**
 * Launch a job with the parameters provided. JSR-352 supports restarting of jobs with a
 * new set of parameters. This method exposes this functionality
 *
 * @param jobExecutionId the job execution to restart
 * @param params the job parameters to use in the restart
 * @return the resulting {@link JobExecution} if successful
 *
 * @throws NoSuchJobExecutionException thrown if job execution specified does not exist
 * @throws NoSuchJobException thrown if job specified does not exist
 * @throws JobExecutionAlreadyRunningException thrown if job is already executing
 * @throws JobRestartException thrown if job failed to restart
 * @throws JobInstanceAlreadyCompleteException thrown if job was already complete
 * @throws JobParametersInvalidException thrown if job parameters are invalid
 */
JobExecution restart(Long jobExecutionId, JobParameters params)
		throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException,
		JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException, JobParametersInvalidException;
 
Example #16
Source File: JobService.java    From spring-cloud-dataflow with Apache License 2.0 2 votes vote down vote up
/**
 * Launch a job with the parameters provided.
 * 
 * @param jobExecutionId the job execution to restart
 * @return the resulting {@link JobExecution} if successful
 * 
 * @throws NoSuchJobExecutionException thrown if job execution specified does not exist
 * @throws NoSuchJobException thrown if job specified does not exist
 * @throws JobExecutionAlreadyRunningException thrown if job is already executing
 * @throws JobRestartException thrown if job failed to restart
 * @throws JobInstanceAlreadyCompleteException thrown if job was already complete
 * @throws JobParametersInvalidException thrown if job parameters are invalid
 */
JobExecution restart(Long jobExecutionId) throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException,
		JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException, JobParametersInvalidException;
 
Example #17
Source File: JobService.java    From spring-cloud-dataflow with Apache License 2.0 2 votes vote down vote up
/**
 * Launch a job with the parameters provided. If an instance with the parameters provided
 * has already failed (and is not abandoned) it will be restarted.
 * 
 * @param jobName the job name
 * @param params the {@link JobParameters}
 * @return the resulting {@link JobExecution} if successful
 * 
 * @throws NoSuchJobException thrown if job specified does not exist
 * @throws JobExecutionAlreadyRunningException thrown if job is already executing
 * @throws JobRestartException thrown if job failed to restart
 * @throws JobInstanceAlreadyCompleteException thrown if job was already complete
 * @throws JobParametersInvalidException thrown if job parameters are invalid
 */
JobExecution launch(String jobName, JobParameters params) throws NoSuchJobException,
		JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
		JobParametersInvalidException;