List of usage examples for org.springframework.batch.core JobExecution getExitStatus
public ExitStatus getExitStatus()
From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java
/** * Batch Job? ./* w ww . j a 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:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java
/** * Batch Job? ./*from w ww . 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:org.cbioportal.annotation.AnnotationPipeline.java
private static void launchJob(String[] args, String filename, String outputFilename, String isoformOverride, String errorReportLocation, boolean replace, boolean verbose) throws Exception { SpringApplication app = new SpringApplication(AnnotationPipeline.class); ConfigurableApplicationContext ctx = app.run(args); JobLauncher jobLauncher = ctx.getBean(JobLauncher.class); Job annotationJob = ctx.getBean(BatchConfiguration.ANNOTATION_JOB, Job.class); JobParameters jobParameters = new JobParametersBuilder().addString("filename", filename) .addString("outputFilename", outputFilename).addString("replace", String.valueOf(replace)) .addString("isoformOverride", isoformOverride).addString("errorReportLocation", errorReportLocation) .addString("verbose", String.valueOf(verbose)).toJobParameters(); JobExecution jobExecution = jobLauncher.run(annotationJob, jobParameters); if (!jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) { System.exit(2);//from ww w.j av a2 s .c om } }
From source file:org.springframework.batch.core.job.AbstractJob.java
/** * Run the specified job, handling all listener and repository calls, and * delegating the actual processing to {@link #doExecute(JobExecution)}. * * @see Job#execute(JobExecution)/*from ww w .j a va 2 s . c om*/ * @throws StartLimitExceededException * if start limit of one of the steps was exceeded */ @Override public final void execute(JobExecution execution) { if (logger.isDebugEnabled()) { logger.debug("Job execution starting: " + execution); } JobSynchronizationManager.register(execution); try { jobParametersValidator.validate(execution.getJobParameters()); if (execution.getStatus() != BatchStatus.STOPPING) { execution.setStartTime(new Date()); updateStatus(execution, BatchStatus.STARTED); listener.beforeJob(execution); try { doExecute(execution); if (logger.isDebugEnabled()) { logger.debug("Job execution complete: " + execution); } } catch (RepeatException e) { throw e.getCause(); } } else { // The job was already stopped before we even got this far. Deal // with it in the same way as any other interruption. execution.setStatus(BatchStatus.STOPPED); execution.setExitStatus(ExitStatus.COMPLETED); if (logger.isDebugEnabled()) { logger.debug("Job execution was stopped: " + execution); } } } catch (JobInterruptedException e) { logger.info("Encountered interruption executing job: " + e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Full exception", e); } execution.setExitStatus(getDefaultExitStatusForFailure(e, execution)); execution.setStatus(BatchStatus.max(BatchStatus.STOPPED, e.getStatus())); execution.addFailureException(e); } catch (Throwable t) { logger.error("Encountered fatal error executing job", t); execution.setExitStatus(getDefaultExitStatusForFailure(t, execution)); execution.setStatus(BatchStatus.FAILED); execution.addFailureException(t); } finally { try { if (execution.getStatus().isLessThanOrEqualTo(BatchStatus.STOPPED) && execution.getStepExecutions().isEmpty()) { ExitStatus exitStatus = execution.getExitStatus(); ExitStatus newExitStatus = ExitStatus.NOOP .addExitDescription("All steps already completed or no steps configured for this job."); execution.setExitStatus(exitStatus.and(newExitStatus)); } execution.setEndTime(new Date()); try { listener.afterJob(execution); } catch (Exception e) { logger.error("Exception encountered in afterStep callback", e); } jobRepository.update(execution); } finally { JobSynchronizationManager.release(); } } }
From source file:org.springframework.batch.core.jsr.configuration.xml.RetryListenerTests.java
@Test @SuppressWarnings("resource") public void testReadRetryExhausted() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/jsr/configuration/xml/RetryReadListenerExhausted.xml"); JobLauncher jobLauncher = context.getBean(JobLauncher.class); JobExecution jobExecution = jobLauncher.run(context.getBean(Job.class), new JobParameters()); List<Throwable> failureExceptions = jobExecution.getAllFailureExceptions(); assertTrue("Expected 1 failure exceptions", failureExceptions.size() == 1); assertTrue("Failure exception must be of type RetryException", (failureExceptions.get(0) instanceof RetryException)); assertTrue("Exception cause must be of type IllegalArgumentException", (failureExceptions.get(0).getCause() instanceof IllegalArgumentException)); assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus()); }
From source file:org.springframework.batch.core.jsr.configuration.xml.RetryListenerTests.java
@Test @SuppressWarnings("resource") public void testReadRetryOnce() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/jsr/configuration/xml/RetryReadListenerRetryOnce.xml"); JobLauncher jobLauncher = context.getBean(JobLauncher.class); JobExecution jobExecution = jobLauncher.run(context.getBean(Job.class), new JobParameters()); Collection<StepExecution> stepExecutions = jobExecution.getStepExecutions(); assertEquals(1, stepExecutions.size()); StepExecution stepExecution = stepExecutions.iterator().next(); assertEquals(1, stepExecution.getCommitCount()); assertEquals(2, stepExecution.getReadCount()); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); }
From source file:org.springframework.batch.core.jsr.configuration.xml.RetryListenerTests.java
@Test @SuppressWarnings("resource") public void testReadRetryExceptionInListener() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/batch/core/jsr/configuration/xml/RetryReadListenerListenerException.xml"); JobLauncher jobLauncher = context.getBean(JobLauncher.class); JobExecution jobExecution = jobLauncher.run(context.getBean(Job.class), new JobParameters()); List<Throwable> failureExceptions = jobExecution.getAllFailureExceptions(); assertTrue("Failure exceptions must equal one", failureExceptions.size() == 1); assertTrue("Failure exception must be of type RetryException", (failureExceptions.get(0) instanceof RetryException)); assertTrue("Exception cause must be of type BatchRuntimeException", (failureExceptions.get(0).getCause() instanceof BatchRuntimeException)); assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus()); }
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 {//from w w w . ja 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.SimpleJobLauncher.java
/** * Run the provided job with the given {@link JobParameters}. The * {@link JobParameters} will be used to determine if this is an execution * of an existing job instance, or if a new one should be created. * * @param job the job to be run.//from w w w . j a va 2s .c o m * @param jobParameters the {@link JobParameters} for this particular * execution. * @return JobExecutionAlreadyRunningException if the JobInstance already * exists and has an execution already running. * @throws JobRestartException if the execution would be a re-start, but a * re-start is either not allowed or not needed. * @throws JobInstanceAlreadyCompleteException if this instance has already * completed successfully * @throws JobParametersInvalidException */ @Override public JobExecution run(final Job job, final JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { Assert.notNull(job, "The Job must not be null."); Assert.notNull(jobParameters, "The JobParameters must not be null."); final JobExecution jobExecution; JobExecution lastExecution = jobRepository.getLastJobExecution(job.getName(), jobParameters); if (lastExecution != null) { if (!job.isRestartable()) { throw new JobRestartException("JobInstance already exists and is not restartable"); } /* * validate here if it has stepExecutions that are UNKNOWN, STARTING, STARTED and STOPPING * retrieve the previous execution and check */ for (StepExecution execution : lastExecution.getStepExecutions()) { BatchStatus status = execution.getStatus(); if (status.isRunning() || status == BatchStatus.STOPPING) { throw new JobExecutionAlreadyRunningException( "A job execution for this job is already running: " + lastExecution); } else if (status == BatchStatus.UNKNOWN) { throw new JobRestartException("Cannot restart step [" + execution.getStepName() + "] 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."); } } } // Check the validity of the parameters before doing creating anything // in the repository... job.getJobParametersValidator().validate(jobParameters); /* * There is a very small probability that a non-restartable job can be * restarted, but only if another process or thread manages to launch * <i>and</i> fail a job execution for this instance between the last * assertion and the next method returning successfully. */ jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters); try { taskExecutor.execute(new Runnable() { @Override public void run() { try { logger.info("Job: [" + job + "] launched with the following parameters: [" + jobParameters + "]"); job.execute(jobExecution); logger.info("Job: [" + job + "] completed with the following parameters: [" + jobParameters + "] and the following status: [" + jobExecution.getStatus() + "]"); } catch (Throwable t) { logger.info("Job: [" + job + "] failed unexpectedly and fatally with the following parameters: [" + jobParameters + "]", t); rethrow(t); } } private void rethrow(Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } throw new IllegalStateException(t); } }); } catch (TaskRejectedException e) { jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); } return jobExecution; }
From source file:org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.java
/** * * SQL implementation using Sequences via the Spring incrementer * abstraction. Once a new id has been obtained, the JobExecution is saved * via a SQL INSERT statement.//www .j a v a 2 s . c o m * * @see JobExecutionDao#saveJobExecution(JobExecution) * @throws IllegalArgumentException if jobExecution is null, as well as any * of it's fields to be persisted. */ @Override public void saveJobExecution(JobExecution jobExecution) { validateJobExecution(jobExecution); jobExecution.incrementVersion(); jobExecution.setId(jobExecutionIncrementer.nextLongValue()); Object[] parameters = new Object[] { jobExecution.getId(), jobExecution.getJobId(), jobExecution.getStartTime(), jobExecution.getEndTime(), jobExecution.getStatus().toString(), jobExecution.getExitStatus().getExitCode(), jobExecution.getExitStatus().getExitDescription(), jobExecution.getVersion(), jobExecution.getCreateTime(), jobExecution.getLastUpdated(), jobExecution.getJobConfigurationName() }; getJdbcTemplate().update(getQuery(SAVE_JOB_EXECUTION), parameters, new int[] { Types.BIGINT, Types.BIGINT, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR }); insertJobParameters(jobExecution.getId(), jobExecution.getJobParameters()); }