List of usage examples for org.springframework.batch.core ExitStatus FAILED
ExitStatus FAILED
To view the source code for org.springframework.batch.core ExitStatus FAILED.
Click Source Link
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 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.jsr.launch.JsrJobOperator.java
/** * Creates a child {@link ApplicationContext} for the job being requested based upon * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/<jobName>.xml * configuration and restart the job.// www.j av a2 s. co m * * @param executionId the database id of the job execution to be restarted. * @param params any job parameters to be used during the execution of this job. * @throws JobExecutionAlreadyCompleteException thrown if the requested job execution has * a status of COMPLETE * @throws NoSuchJobExecutionException throw if the requested job execution does not exist * in the repository * @throws JobExecutionNotMostRecentException thrown if the requested job execution is not * the most recent attempt for the job instance it's related to. * @throws JobRestartException thrown for any general errors during the job restart process */ @Override public long restart(long executionId, Properties params) throws JobExecutionAlreadyCompleteException, NoSuchJobExecutionException, JobExecutionNotMostRecentException, JobRestartException, JobSecurityException { org.springframework.batch.core.JobExecution previousJobExecution = jobExplorer.getJobExecution(executionId); if (previousJobExecution == null) { throw new NoSuchJobExecutionException("No JobExecution found for id: [" + executionId + "]"); } else if (previousJobExecution.getStatus().equals(BatchStatus.COMPLETED)) { throw new JobExecutionAlreadyCompleteException("The requested job has already completed"); } List<org.springframework.batch.core.JobExecution> previousExecutions = jobExplorer .getJobExecutions(previousJobExecution.getJobInstance()); for (org.springframework.batch.core.JobExecution jobExecution : previousExecutions) { if (jobExecution.getCreateTime().compareTo(previousJobExecution.getCreateTime()) > 0) { throw new JobExecutionNotMostRecentException( "The requested JobExecution to restart was not the most recently run"); } if (jobExecution.getStatus().equals(BatchStatus.ABANDONED)) { throw new JobRestartException("JobExecution ID: " + jobExecution.getId() + " is abandoned and attempted to be restarted."); } } final String jobName = previousJobExecution.getJobInstance().getJobName(); Properties jobRestartProperties = getJobRestartProperties(params, previousJobExecution); final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(jobRestartProperties); batchContext.setValidating(false); Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); Resource jobXml = new ClassPathResource(previousJobExecution.getJobConfigurationName()); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); batchContext.setParent(baseContext); try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobRestartException(e); } final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(jobRestartProperties); jobExecution = jobRepository.createJobExecution(previousJobExecution.getJobInstance(), jobParameters, previousJobExecution.getJobConfigurationName()); } catch (Exception e) { throw new JobRestartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final Job job = batchContext.getBean(Job.class); if (!job.isRestartable()) { throw new JobRestartException("Job " + jobName + " is not restartable"); } semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobRestartException(exceptionHolder.get(0)); } } catch (Exception e) { jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobRestartException(e); } return jobExecution.getId(); }
From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java
/** * Creates a child {@link ApplicationContext} for the job being requested based upon * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/<jobName>.xml * configuration and launches the job. Per JSR-352, calls to this method will always * create a new {@link JobInstance} (and related {@link JobExecution}). * * @param jobName the name of the job XML file without the .xml that is located within the * /META-INF/batch-jobs directory./*from w w w . ja va 2s . c o m*/ * @param params any job parameters to be used during the execution of this job. */ @Override public long start(String jobName, Properties params) throws JobStartException, JobSecurityException { final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params); batchContext.setValidating(false); Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml"; Resource jobXml = new ClassPathResource(jobConfigurationLocation); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); if (baseContext != null) { batchContext.setParent(baseContext); } else { batchContext.getBeanFactory().registerSingleton("jobExplorer", jobExplorer); batchContext.getBeanFactory().registerSingleton("jobRepository", jobRepository); batchContext.getBeanFactory().registerSingleton("jobParametersConverter", jobParametersConverter); batchContext.getBeanFactory().registerSingleton("transactionManager", transactionManager); } try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobStartException(e); } Assert.notNull(jobName, "The job name must not be null."); final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(params); String[] jobNames = batchContext.getBeanNamesForType(Job.class); if (jobNames == null || jobNames.length <= 0) { throw new BatchRuntimeException("No Job defined in current context"); } org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0], jobParameters); jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation); } catch (Exception e) { throw new JobStartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final Job job = batchContext.getBean(Job.class); semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobStartException(exceptionHolder.get(0)); } } catch (Exception e) { if (jobRegistry.exists(jobExecution.getId())) { jobRegistry.remove(jobExecution); } jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobStartException(e); } return jobExecution.getId(); }
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 va 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 ava2 s . 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.launch.support.SimpleJvmExitCodeMapper.java
public SimpleJvmExitCodeMapper() { mapping = new HashMap<String, Integer>(); mapping.put(ExitStatus.COMPLETED.getExitCode(), JVM_EXITCODE_COMPLETED); mapping.put(ExitStatus.FAILED.getExitCode(), JVM_EXITCODE_GENERIC_ERROR); mapping.put(ExitCodeMapper.JOB_NOT_PROVIDED, JVM_EXITCODE_JOB_ERROR); mapping.put(ExitCodeMapper.NO_SUCH_JOB, JVM_EXITCODE_JOB_ERROR); }
From source file:org.springframework.batch.core.step.AbstractStep.java
/** * Default mapping from throwable to {@link ExitStatus}. Clients can modify the exit code using a * {@link StepExecutionListener}.//from w w w . j av a2s.c o m * * @param ex the cause of the failure * @return an {@link ExitStatus} */ private ExitStatus getDefaultExitStatusForFailure(Throwable ex) { ExitStatus exitStatus; if (ex instanceof JobInterruptedException || ex.getCause() instanceof JobInterruptedException) { exitStatus = ExitStatus.STOPPED.addExitDescription(JobInterruptedException.class.getName()); } else if (ex instanceof NoSuchJobException || ex.getCause() instanceof NoSuchJobException) { exitStatus = new ExitStatus(ExitCodeMapper.NO_SUCH_JOB, ex.getClass().getName()); } else { exitStatus = ExitStatus.FAILED.addExitDescription(ex); } return exitStatus; }
From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanTests.java
/** * Non-skippable (and non-fatal) exception causes failure immediately. * * @throws Exception/* w w w . j a v a 2 s.c o m*/ */ @SuppressWarnings("unchecked") @Test public void testNonSkippableExceptionOnRead() throws Exception { reader.setFailures("2"); // nothing is skippable factory.setSkippableExceptionClasses(getExceptionMap(NonExistentException.class)); Step step = factory.getObject(); step.execute(stepExecution); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); assertEquals(ExitStatus.FAILED.getExitCode(), stepExecution.getExitStatus().getExitCode()); assertTrue( stepExecution.getExitStatus().getExitDescription().contains("Non-skippable exception during read")); assertStepExecutionsAreEqual(stepExecution, repository.getLastStepExecution(jobExecution.getJobInstance(), step.getName())); }
From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanTests.java
@SuppressWarnings("unchecked") @Test/*from w w w .j av a 2 s .c o m*/ public void testNonSkippableException() throws Exception { // nothing is skippable factory.setSkippableExceptionClasses(getExceptionMap(NonExistentException.class)); factory.setCommitInterval(1); // no failures on read reader.setItems("1", "2", "3", "4", "5"); writer.setFailures("1"); Step step = factory.getObject(); step.execute(stepExecution); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); assertEquals(1, reader.getRead().size()); assertEquals(ExitStatus.FAILED.getExitCode(), stepExecution.getExitStatus().getExitCode()); assertTrue(stepExecution.getExitStatus().getExitDescription().contains("Intended Failure")); assertStepExecutionsAreEqual(stepExecution, repository.getLastStepExecution(jobExecution.getJobInstance(), step.getName())); }