Example usage for org.springframework.batch.core ExitStatus COMPLETED

List of usage examples for org.springframework.batch.core ExitStatus COMPLETED

Introduction

In this page you can find the example usage for org.springframework.batch.core ExitStatus COMPLETED.

Prototype

ExitStatus COMPLETED

To view the source code for org.springframework.batch.core ExitStatus COMPLETED.

Click Source Link

Document

Convenient constant value representing finished processing.

Usage

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  w ww .j a  va2 s. c  o m
    }
}

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)//  w ww  . j  av a 2 s  .  c o  m
 * @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 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.launch.support.CommandLineJobRunner.java

@SuppressWarnings("resource")
int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {/* w  ww . j a  va2  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.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

/**
 * Template method for step execution logic - calls abstract methods for resource initialization (
 * {@link #open(ExecutionContext)}), execution logic ({@link #doExecute(StepExecution)}) and resource closing (
 * {@link #close(ExecutionContext)})./*  w w w.  j a v a2 s . c o m*/
 */
@Override
public final void execute(StepExecution stepExecution)
        throws JobInterruptedException, UnexpectedJobExecutionException {

    if (logger.isDebugEnabled()) {
        logger.debug("Executing: id=" + stepExecution.getId());
    }
    stepExecution.setStartTime(new Date());
    stepExecution.setStatus(BatchStatus.STARTED);
    getJobRepository().update(stepExecution);

    // Start with a default value that will be trumped by anything
    ExitStatus exitStatus = ExitStatus.EXECUTING;

    doExecutionRegistration(stepExecution);

    try {
        getCompositeListener().beforeStep(stepExecution);
        open(stepExecution.getExecutionContext());

        try {
            doExecute(stepExecution);
        } catch (RepeatException e) {
            throw e.getCause();
        }
        exitStatus = ExitStatus.COMPLETED.and(stepExecution.getExitStatus());

        // Check if someone is trying to stop us
        if (stepExecution.isTerminateOnly()) {
            throw new JobInterruptedException("JobExecution interrupted.");
        }

        // Need to upgrade here not set, in case the execution was stopped
        stepExecution.upgradeStatus(BatchStatus.COMPLETED);
        if (logger.isDebugEnabled()) {
            logger.debug("Step execution success: id=" + stepExecution.getId());
        }
    } catch (Throwable e) {
        stepExecution.upgradeStatus(determineBatchStatus(e));
        exitStatus = exitStatus.and(getDefaultExitStatusForFailure(e));
        stepExecution.addFailureException(e);
        if (stepExecution.getStatus() == BatchStatus.STOPPED) {
            logger.info(String.format("Encountered interruption executing step %s in job %s : %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName(), e.getMessage()));
            if (logger.isDebugEnabled()) {
                logger.debug("Full exception", e);
            }
        } else {
            logger.error(String.format("Encountered an error executing step %s in job %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }
    } finally {

        try {
            // Update the step execution to the latest known value so the
            // listeners can act on it
            exitStatus = exitStatus.and(stepExecution.getExitStatus());
            stepExecution.setExitStatus(exitStatus);
            exitStatus = exitStatus.and(getCompositeListener().afterStep(stepExecution));
        } catch (Exception e) {
            logger.error(String.format("Exception in afterStep callback in step %s in job %s", name,
                    stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        try {
            getJobRepository().updateExecutionContext(stepExecution);
        } catch (Exception e) {
            stepExecution.setStatus(BatchStatus.UNKNOWN);
            exitStatus = exitStatus.and(ExitStatus.UNKNOWN);
            stepExecution.addFailureException(e);
            logger.error(String.format(
                    "Encountered an error saving batch meta data for step %s in job %s. "
                            + "This job is now in an unknown state and should not be restarted.",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        stepExecution.setEndTime(new Date());
        stepExecution.setExitStatus(exitStatus);

        try {
            getJobRepository().update(stepExecution);
        } catch (Exception e) {
            stepExecution.setStatus(BatchStatus.UNKNOWN);
            stepExecution.setExitStatus(exitStatus.and(ExitStatus.UNKNOWN));
            stepExecution.addFailureException(e);
            logger.error(String.format(
                    "Encountered an error saving batch meta data for step %s in job %s. "
                            + "This job is now in an unknown state and should not be restarted.",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
        }

        try {
            close(stepExecution.getExecutionContext());
        } catch (Exception e) {
            logger.error(String.format("Exception while closing step execution resources in step %s in job %s",
                    name, stepExecution.getJobExecution().getJobInstance().getJobName()), e);
            stepExecution.addFailureException(e);
        }

        doExecutionRelease();

        if (logger.isDebugEnabled()) {
            logger.debug("Step execution complete: " + stepExecution.getSummary());
        }
    }
}

From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanRetryTests.java

@Test
public void testProcessAllItemsWhenErrorInWriter() throws Exception {
    final int RETRY_LIMIT = 3;
    final List<String> ITEM_LIST = Arrays.asList("a", "b", "c");
    ItemWriter<String> failingWriter = new ItemWriter<String>() {
        @Override//from  w w  w. ja va 2s  . c  o m
        public void write(List<? extends String> data) throws Exception {
            int count = 0;
            for (String item : data) {
                if (count++ == 2) {
                    throw new Exception("Planned failure in writer");
                }
                written.add(item);
            }
        }
    };

    ItemProcessor<String, String> processor = new ItemProcessor<String, String>() {
        @Override
        public String process(String item) throws Exception {
            processed.add(item);
            return item;
        }
    };
    ItemReader<String> reader = new ListItemReader<String>(ITEM_LIST);
    factory.setCommitInterval(3);
    factory.setRetryLimit(RETRY_LIMIT);
    factory.setSkipLimit(1);
    @SuppressWarnings("unchecked")
    Map<Class<? extends Throwable>, Boolean> exceptionMap = getExceptionMap(Exception.class);
    factory.setSkippableExceptionClasses(exceptionMap);
    factory.setItemReader(reader);
    factory.setItemProcessor(processor);
    factory.setItemWriter(failingWriter);
    Step step = factory.getObject();

    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(ExitStatus.COMPLETED.getExitCode(), stepExecution.getExitStatus().getExitCode());
    /*
     * Each chunk tried up to RETRY_LIMIT, then the scan processes each item
     * once, identifying the skip as it goes
     */
    assertEquals((RETRY_LIMIT + 1) * ITEM_LIST.size(), processed.size());
}

From source file:org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter.java

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
    if (!(stepExecution.getStatus() == BatchStatus.COMPLETED)) {
        return ExitStatus.EXECUTING;
    }/*from   w ww  .  jav a2 s .  co m*/
    long expecting = localState.getExpecting();
    boolean timedOut;
    try {
        logger.debug("Waiting for results in step listener...");
        timedOut = !waitForResults();
        logger.debug("Finished waiting for results in step listener.");
    } catch (RuntimeException e) {
        logger.debug("Detected failure waiting for results in step listener.", e);
        stepExecution.setStatus(BatchStatus.FAILED);
        return ExitStatus.FAILED.addExitDescription(e.getClass().getName() + ": " + e.getMessage());
    } finally {

        if (logger.isDebugEnabled()) {
            logger.debug("Finished waiting for results in step listener.  Still expecting: "
                    + localState.getExpecting());
        }

        for (StepContribution contribution : getStepContributions()) {
            stepExecution.apply(contribution);
        }
    }
    if (timedOut) {
        stepExecution.setStatus(BatchStatus.FAILED);
        return ExitStatus.FAILED.addExitDescription(
                "Timed out waiting for " + localState.getExpecting() + " backlog at end of step");
    }
    return ExitStatus.COMPLETED.addExitDescription("Waited for " + expecting + " results.");
}

From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTests.java

@Test
public void testSimple() throws Exception {
    FileSystem fs = FileSystem.get(configuration);
    Path p1 = new Path("/qux/foo/bar.txt");
    fs.delete(p1, true);/*from   w w w. j a va2 s  . c  o m*/
    Path p2 = new Path("/qux/foo/baz.txt");
    fs.delete(p2, true);
    assertFalse(fs.exists(p1));
    assertFalse(fs.exists(p2));

    Map<String, JobParameter> params = new HashMap<String, JobParameter>();
    params.put("remoteDirectory", new JobParameter("/foo/"));
    params.put("hdfsDirectory", new JobParameter("/qux"));
    JobParameters parameters = new JobParameters(params);
    JobExecution execution = launcher.run(job, parameters);
    assertEquals(ExitStatus.COMPLETED, execution.getExitStatus());

    assertTrue(fs.exists(p1));
    assertTrue(fs.exists(p2));

    FSDataInputStream stream = fs.open(p1);
    byte[] out = new byte[9];
    stream.readFully(out);
    stream.close();
    assertEquals("foobarbaz", new String(out));

    stream = fs.open(p2);
    stream.readFully(out);
    stream.close();
    assertEquals("foobarbaz", new String(out));
}

From source file:org.springframework.batch.integration.x.RemoteFileToTmpTests.java

@Test
public void testSimple() throws Exception {
    Map<String, JobParameter> params = new HashMap<String, JobParameter>();
    params.put("remoteDirectory", new JobParameter("/foo/"));
    params.put("hdfsDirectory", new JobParameter("/qux"));
    JobParameters parameters = new JobParameters(params);
    JobExecution execution = launcher.run(job, parameters);
    assertEquals(ExitStatus.COMPLETED, execution.getExitStatus());

    File file = new File(tmpDir, "_foo_bar.txt");
    assertTrue(file.exists());//w  ww.j  a v  a 2s  .  co m
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileCopyUtils.copy(new FileInputStream(file), baos);
    assertEquals("foo", new String(baos.toByteArray()));
    file.delete();

    file = new File(tmpDir, "_foo_baz.txt");
    assertTrue(file.exists());
    baos = new ByteArrayOutputStream();
    FileCopyUtils.copy(new FileInputStream(file), baos);
    assertEquals("foo", new String(baos.toByteArray()));
    file.delete();
}