List of usage examples for org.springframework.batch.core JobExecution getJobInstance
public JobInstance getJobInstance()
From source file:org.springframework.batch.admin.domain.JobExecutionInfoResource.java
public JobExecutionInfoResource(JobExecution jobExecution, TimeZone timeZone) { if (timeZone != null) { this.timeZone = timeZone; } else {//from www . j av a 2s .c o m this.timeZone = TimeZone.getTimeZone("UTC"); } this.executionId = jobExecution.getId(); this.jobId = jobExecution.getJobId(); this.stepExecutionCount = jobExecution.getStepExecutions().size(); this.jobParameters = jobExecution.getJobParameters(); this.status = jobExecution.getStatus(); this.exitStatus = jobExecution.getExitStatus(); this.jobConfigurationName = jobExecution.getJobConfigurationName(); this.failureExceptions = jobExecution.getFailureExceptions(); Map<String, Object> executionContextEntires = new HashMap<String, Object>( jobExecution.getExecutionContext().size()); for (Map.Entry<String, Object> stringObjectEntry : jobExecution.getExecutionContext().entrySet()) { executionContextEntires.put(stringObjectEntry.getKey(), stringObjectEntry.getValue()); } this.executionContext = executionContextEntires; this.version = jobExecution.getVersion(); JobInstance jobInstance = jobExecution.getJobInstance(); if (jobInstance != null) { this.jobName = jobInstance.getJobName(); BatchStatus status = jobExecution.getStatus(); this.restartable = status.isGreaterThan(BatchStatus.STOPPING) && status.isLessThan(BatchStatus.ABANDONED); this.abandonable = status.isGreaterThan(BatchStatus.STARTED) && status != BatchStatus.ABANDONED; this.stoppable = status.isLessThan(BatchStatus.STOPPING) && status != BatchStatus.COMPLETED; } else { this.jobName = "?"; } this.dateFormat = this.dateFormat.withZone(DateTimeZone.forTimeZone(timeZone)); this.createDate = dateFormat.print(jobExecution.getCreateTime().getTime()); this.lastUpdated = dateFormat.print(jobExecution.getLastUpdated().getTime()); if (jobExecution.getStartTime() != null) { this.startTime = dateFormat.print(jobExecution.getStartTime().getTime()); this.endTime = dateFormat.print(jobExecution.getEndTime().getTime()); } }
From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java
/** * Batch Job? .//from w w w .j av a2 s.co m * ? , Job ? / JobExecutionID, Job Parameter * CommandLineRunner Option ? . * * @param jobPath : Job Context ? XML ? * @param jobIdentifier : Job ? /JobExecutionID * @param parameters : Job Parameter * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon) */ public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; try { // ApplicationContext ?. 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."); // ? Batch Job? , ? Batch Job? ? JobExplorer ?. 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."); } // Job? ?? . String jobName = jobIdentifier; // JobParameters ?. 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)."); // Batch Job? . 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()); } // ? Batch Job? ? abandon . 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()); } // Batch Job? . 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.getJobInstance().getJobParameters(); jobName = jobExecution.getJobInstance().getJobName(); } Job job; // JobLocator Job? null? ApplicationContext? Job? . if (jobLocator != null) { job = jobLocator.getJob(jobName); } else { job = (Job) context.getBean(jobName); } // ? Batch Job? Job Parameters ?. 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); } // Batch Job? . JobExecution jobExecution = launcher.run(job, jobParameters); logger.warn("EgovCommandLineRunner's Job Information"); logger.warn("jobName=" + jobExecution.getJobInstance().getJobName()); logger.warn("jobParamters=" + jobParameters.toString()); logger.warn("jobExecutionTime=" + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s"); return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode()); } catch (Throwable e) { String message = "Job Terminated in error: " + e.getMessage(); logger.error(message, e); EgovCommandLineRunner.message = message; return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()); } finally { if (context != null) { context.close(); } } }
From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java
/** * Batch Job? ./*from w ww. ja v a 2 s .c om*/ * ? , Job ? / JobExecutionID, Job Parameter * CommandLineRunner Option ? . * * @param jobPath : Job Context ? XML ? * @param jobIdentifier : Job ? /JobExecutionID * @param parameters : Job Parameter * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon) */ public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; try { // ApplicationContext ?. 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."); // ? Batch Job? , ? Batch Job? ? JobExplorer ?. 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."); } // Job? ?? . String jobName = jobIdentifier; // JobParameters ?. 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)."); // Batch Job? . 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()); } // ? Batch Job? ? abandon . 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()); } // Batch Job? . 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.getJobInstance().getJobParameters(); jobName = jobExecution.getJobInstance().getJobName(); } Job job; // JobLocator Job? null? ApplicationContext? Job? . if (jobLocator != null) { job = jobLocator.getJob(jobName); } else { job = (Job) context.getBean(jobName); } // ? Batch Job? Job Parameters ?. 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); } // Batch Job? . JobExecution jobExecution = launcher.run(job, jobParameters); logger.warn("CommandLineRunner's Job Information"); logger.warn("jobName=" + jobExecution.getJobInstance().getJobName()); logger.warn("jobParamters=" + jobParameters.toString()); logger.warn("jobExecutionTime=" + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s"); return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode()); } catch (Throwable e) { String message = "Job Terminated in error: " + e.getMessage(); logger.error(message, e); CommandLineRunner.message = message; return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()); } finally { if (context != null) { context.close(); } } }
From source file:org.springframework.batch.admin.web.JobExecutionController.java
@RequestMapping(value = "/jobs/executions/{jobExecutionId}", method = RequestMethod.GET) public String detail(Model model, @PathVariable Long jobExecutionId, @ModelAttribute("date") Date date, Errors errors) {//from w w w . j a v a2 s. c o m try { JobExecution jobExecution = jobService.getJobExecution(jobExecutionId); model.addAttribute(new JobExecutionInfo(jobExecution, timeZone)); String jobName = jobExecution.getJobInstance().getJobName(); Collection<String> stepNames = new HashSet<String>(jobService.getStepNamesForJob(jobName)); Collection<StepExecution> stepExecutions = new ArrayList<StepExecution>( jobExecution.getStepExecutions()); Collection<StepExecutionInfo> stepExecutionInfos = new ArrayList<StepExecutionInfo>(); for (String name : stepNames) { boolean found = false; for (Iterator<StepExecution> iterator = stepExecutions.iterator(); iterator.hasNext();) { StepExecution stepExecution = iterator.next(); if (stepExecution.getStepName().equals(name)) { stepExecutionInfos.add(new StepExecutionInfo(stepExecution, timeZone)); iterator.remove(); found = true; } } if (!found) { stepExecutionInfos.add(new StepExecutionInfo(jobName, jobExecutionId, name, timeZone)); } } model.addAttribute("stepExecutionInfos", stepExecutionInfos); } catch (NoSuchJobExecutionException e) { errors.reject("no.such.job.execution", new Object[] { jobExecutionId }, "There is no such job execution (" + jobExecutionId + ")"); } catch (NoSuchJobException e) { errors.reject("no.such.job", new Object[] { jobExecutionId }, "There is no such job with exeuction id (" + jobExecutionId + ")"); } return "jobs/execution"; }
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."); }// www . jav a2s .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.job.SimpleStepHandler.java
/** * Given a step and configuration, return true if the step should start, * false if it should not, and throw an exception if the job should finish. * @param lastStepExecution the last step execution * @param jobExecution/*ww w.j a va2 s .co m*/ * @param step * * @throws StartLimitExceededException if the start limit has been exceeded * for this step * @throws JobRestartException if the job is in an inconsistent state from * an earlier failure */ protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step) throws JobRestartException, StartLimitExceededException { BatchStatus stepStatus; if (lastStepExecution == null) { stepStatus = BatchStatus.STARTING; } else { stepStatus = lastStepExecution.getStatus(); } if (stepStatus == BatchStatus.UNKNOWN) { throw new JobRestartException("Cannot restart step 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."); } if ((stepStatus == BatchStatus.COMPLETED && !step.isAllowStartIfComplete()) || stepStatus == BatchStatus.ABANDONED) { // step is complete, false should be returned, indicating that the // step should not be started logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution); return false; } if (jobRepository.getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step .getStartLimit()) { // step start count is less than start max, return true return true; } else { // start max has been exceeded, throw an exception. throw new StartLimitExceededException("Maximum start limit exceeded for step: " + step.getName() + "StartMax: " + step.getStartLimit()); } }
From source file:org.springframework.batch.core.jsr.job.DefaultStepHandler.java
/** * Given a step and configuration, return true if the step should start, * false if it should not, and throw an exception if the job should finish. * @param lastStepExecution the last step execution * @param jobInstance/*from ww w .j a va 2 s .c o m*/ * @param step * * @throws StartLimitExceededException if the start limit has been exceeded * for this step * @throws JobRestartException if the job is in an inconsistent state from * an earlier failure */ @Override protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step) throws JobRestartException, StartLimitExceededException { BatchStatus stepStatus; String restartStep = null; if (lastStepExecution == null) { jobExecution.getExecutionContext().put("batch.startedStep", step.getName()); stepStatus = BatchStatus.STARTING; } else { stepStatus = lastStepExecution.getStatus(); JobExecution lastJobExecution = getLastJobExecution(jobExecution); if (lastJobExecution.getExecutionContext().containsKey("batch.restartStep")) { restartStep = lastJobExecution.getExecutionContext().getString("batch.restartStep"); if (CollectionUtils.isEmpty(jobExecution.getStepExecutions()) && lastJobExecution.getStatus() == BatchStatus.STOPPED && StringUtils.hasText(restartStep)) { if (!restartStep.equals(step.getName()) && !jobExecution.getExecutionContext().containsKey("batch.startedStep")) { logger.info("Job was stopped and should restart at step " + restartStep + ". The current step is " + step.getName()); return false; } else { // Indicates the starting point for execution evaluation per JSR-352 jobExecution.getExecutionContext().put("batch.startedStep", step.getName()); } } } } if (stepStatus == BatchStatus.UNKNOWN) { throw new JobRestartException("Cannot restart step 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."); } if ((stepStatus == BatchStatus.COMPLETED && step.isAllowStartIfComplete() == false) || stepStatus == BatchStatus.ABANDONED) { // step is complete, false should be returned, indicating that the // step should not be started logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution); return false; } if (getJobRepository().getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step .getStartLimit()) { // step start count is less than start max, return true return true; } else { // start max has been exceeded, throw an exception. throw new StartLimitExceededException("Maximum start limit exceeded for step: " + step.getName() + "StartMax: " + step.getStartLimit()); } }
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}./*w ww. ja va 2 s . co m*/ * * @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.CommandLineJobRunner.java
@SuppressWarnings("resource") int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; try {//w ww.jav a 2 s. co 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(); } } }