Example usage for org.springframework.batch.core StepExecution getStatus

List of usage examples for org.springframework.batch.core StepExecution getStatus

Introduction

In this page you can find the example usage for org.springframework.batch.core StepExecution getStatus.

Prototype

public BatchStatus getStatus() 

Source Link

Document

Returns the current status of this step

Usage

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

@Test
public void testRetryWithNoSkip() throws Exception {

    factory.setRetryLimit(4);//from ww w. j  av  a  2 s .  c o m
    factory.setSkipLimit(0);
    ItemReader<String> provider = new ListItemReader<String>(Arrays.asList("b")) {
        @Override
        public String read() {
            String item = super.read();
            provided.add(item);
            count++;
            return item;
        }
    };
    ItemWriter<String> itemWriter = new ItemWriter<String>() {
        @Override
        public void write(List<? extends String> item) throws Exception {
            processed.addAll(item);
            written.addAll(item);
            logger.debug("Write Called! Item: [" + item + "]");
            throw new RuntimeException("Write error - planned but retryable.");
        }
    };
    factory.setItemReader(provider);
    factory.setItemWriter(itemWriter);
    Step step = factory.getObject();

    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());

    List<String> expectedOutput = Arrays.asList(StringUtils.commaDelimitedListToStringArray(""));
    assertEquals(expectedOutput, written);

    assertEquals(0, stepExecution.getSkipCount());
    // [b]
    assertEquals(1, provided.size());
    // the failed items are tried up to the limit (but only precisely so if
    // the commit interval is 1)
    assertEquals("[b, b, b, b, b]", processed.toString());
    // []
    assertEquals(0, recovered.size());
    assertEquals(1, stepExecution.getReadCount());
}

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

@Test
public void testRetryPolicy() throws Exception {
    factory.setRetryPolicy(new SimpleRetryPolicy(4,
            Collections.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true)));
    factory.setSkipLimit(0);//from  w  w w. ja  v  a  2  s  .  com
    ItemReader<String> provider = new ListItemReader<String>(Arrays.asList("b")) {
        @Override
        public String read() {
            String item = super.read();
            provided.add(item);
            count++;
            return item;
        }
    };
    ItemWriter<String> itemWriter = new ItemWriter<String>() {
        @Override
        public void write(List<? extends String> item) throws Exception {
            processed.addAll(item);
            written.addAll(item);
            logger.debug("Write Called! Item: [" + item + "]");
            throw new RuntimeException("Write error - planned but retryable.");
        }
    };
    factory.setItemReader(provider);
    factory.setItemWriter(itemWriter);
    AbstractStep step = (AbstractStep) factory.getObject();

    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());

    List<String> expectedOutput = Arrays.asList(StringUtils.commaDelimitedListToStringArray(""));
    assertEquals(expectedOutput, written);

    assertEquals(0, stepExecution.getSkipCount());
    // [b]
    assertEquals(1, provided.size());
    assertEquals("[b, b, b, b, b]", processed.toString());
    // []
    assertEquals(0, recovered.size());
    assertEquals(1, stepExecution.getReadCount());
}

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

@Test
public void testCacheLimitWithRetry() throws Exception {
    factory.setRetryLimit(2);//from  ww w .  j av a2 s .  c o  m
    factory.setCommitInterval(3);
    // sufficiently high so we never hit it
    factory.setSkipLimit(10);
    // set the cache limit stupidly low
    factory.setRetryContextCache(new MapRetryContextCache(0));
    ItemReader<String> provider = new ItemReader<String>() {
        @Override
        public String read() {
            String item = "" + count;
            provided.add(item);
            count++;
            if (count >= 10) {
                // prevent infinite loop in worst case scenario
                return null;
            }
            return item;
        }
    };
    ItemWriter<String> itemWriter = new ItemWriter<String>() {
        @Override
        public void write(List<? extends String> item) throws Exception {
            processed.addAll(item);
            logger.debug("Write Called! Item: [" + item + "]");
            throw new RuntimeException("Write error - planned but retryable.");
        }
    };
    factory.setItemReader(provider);
    factory.setItemWriter(itemWriter);
    AbstractStep step = (AbstractStep) factory.getObject();

    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());

    // We added a bogus cache so no items are actually skipped
    // because they aren't recognised as eligible
    assertEquals(0, stepExecution.getSkipCount());
    // [0, 1, 2]
    assertEquals(3, provided.size());
    // [0, 1, 2]
    assertEquals(3, processed.size());
    // []
    assertEquals(0, recovered.size());
}

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

@Test
@Ignore //FIXME/* w ww.j av  a 2  s  .c  o  m*/
public void testTransactionException() throws Exception {

    final SkipWriterStub<String> writer = new SkipWriterStub<String>();
    FaultTolerantStepFactoryBean<String, String> factory = new FaultTolerantStepFactoryBean<String, String>();
    factory.setItemWriter(writer);

    @SuppressWarnings("serial")
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource) {
        private boolean failed = false;

        @Override
        protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
            if (writer.getWritten().isEmpty() || failed || !isExistingTransaction(status.getTransaction())) {
                super.doCommit(status);
                return;
            }
            failed = true;
            status.setRollbackOnly();
            super.doRollback(status);
            throw new UnexpectedRollbackException("Planned");
        }
    };

    factory.setBeanName("stepName");
    factory.setTransactionManager(transactionManager);
    factory.setCommitInterval(2);

    ItemReader<String> reader = new ListItemReader<String>(Arrays.asList("1", "2"));
    factory.setItemReader(reader);

    JobRepositoryFactoryBean repositoryFactory = new JobRepositoryFactoryBean();
    repositoryFactory.setDataSource(dataSource);
    repositoryFactory.setTransactionManager(transactionManager);
    repositoryFactory.afterPropertiesSet();
    JobRepository repository = repositoryFactory.getObject();
    factory.setJobRepository(repository);

    JobExecution jobExecution = repository.createJobExecution("job", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution(factory.getName());
    repository.add(stepExecution);

    Step step = factory.getObject();

    step.execute(stepExecution);
    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());

    assertEquals("[]", writer.getCommitted().toString());
}

From source file:org.springframework.batch.core.step.tasklet.AsyncChunkOrientedStepIntegrationTests.java

@Test
@Ignore//w  w  w .ja v  a2 s.  co  m
public void testStatus() throws Exception {

    step.setTasklet(new TestingChunkOrientedTasklet<String>(
            getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }),
            new ItemWriter<String>() {
                @Override
                public void write(List<? extends String> data) throws Exception {
                    written.addAll(data);
                }
            }, chunkOperations));

    final JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters(
            Collections.singletonMap("run.id", new JobParameter(getClass().getName() + ".1"))));
    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);

    jobRepository.add(stepExecution);
    step.execute(stepExecution);
    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    // Need a transaction so one connection is enough to get job execution and its parameters
    StepExecution lastStepExecution = new TransactionTemplate(transactionManager)
            .execute(new TransactionCallback<StepExecution>() {
                @Override
                public StepExecution doInTransaction(TransactionStatus status) {
                    return jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName());
                }
            });
    assertEquals(lastStepExecution, stepExecution);
    assertFalse(lastStepExecution == stepExecution);
}

From source file:org.springframework.batch.core.step.tasklet.AsyncTaskletStepTests.java

/**
 * StepExecution should be updated after every chunk commit.
 *//*from ww w. j a v  a2 s.com*/
@Test
public void testStepExecutionUpdates() throws Exception {

    items = new ArrayList<String>(Arrays.asList(StringUtils.commaDelimitedListToStringArray(
            "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25")));

    setUp();

    JobExecution jobExecution = jobRepository.createJobExecution("JOB", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution(step.getName());

    step.execute(stepExecution);

    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    //      assertEquals(25, stepExecution.getReadCount());
    //      assertEquals(25, processed.size());
    assertTrue(stepExecution.getReadCount() >= 25);
    assertTrue(processed.size() >= 25);

    // System.err.println(stepExecution.getCommitCount());
    // System.err.println(processed);
    // Check commit count didn't spin out of control waiting for other
    // threads to finish...
    assertTrue("Not enough commits: " + stepExecution.getCommitCount(),
            stepExecution.getCommitCount() > processed.size() / 2);
    assertTrue("Too many commits: " + stepExecution.getCommitCount(),
            stepExecution.getCommitCount() <= processed.size() / 2 + throttleLimit + 1);

}

From source file:org.springframework.batch.core.step.tasklet.AsyncTaskletStepTests.java

/**
 * StepExecution should fail immediately on error.
 *//*w  w  w  . j a  v  a  2  s. c  o  m*/
@Test
public void testStepExecutionFails() throws Exception {

    throttleLimit = 1;
    concurrencyLimit = 1;
    items = Arrays.asList("one", "fail", "three", "four");
    setUp();

    JobExecution jobExecution = jobRepository.createJobExecution("JOB", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution(step.getName());

    step.execute(stepExecution);

    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());
    assertEquals(2, stepExecution.getReadCount());
    assertEquals(2, processed.size());

}

From source file:org.springframework.batch.core.step.tasklet.AsyncTaskletStepTests.java

/**
 * StepExecution should fail immediately on error in processor.
 *///from   w w  w .j  a  v  a2  s. c om
@Test
public void testStepExecutionFailsWithProcessor() throws Exception {

    throttleLimit = 1;
    concurrencyLimit = 1;
    items = Arrays.asList("one", "barf", "three", "four");
    itemProcessor = new ItemProcessor<String, String>() {
        @Override
        public String process(String item) throws Exception {
            logger.info("Item: " + item);
            processed.add(item);
            if (item.equals("barf")) {
                throw new RuntimeException("Planned processor error");
            }
            return item;
        }
    };
    setUp();

    JobExecution jobExecution = jobRepository.createJobExecution("JOB", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution(step.getName());

    step.execute(stepExecution);

    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());
    assertEquals(2, stepExecution.getReadCount());
    assertEquals(2, processed.size());

}

From source file:org.springframework.batch.core.step.tasklet.AsyncTaskletStepTests.java

/**
 * StepExecution should fail immediately on error.
 *//* w w  w  . j  a  va2s.  c  om*/
@Test
public void testStepExecutionFailsOnLastItem() throws Exception {

    throttleLimit = 1;
    concurrencyLimit = 1;
    items = Arrays.asList("one", "two", "three", "fail");
    setUp();

    JobExecution jobExecution = jobRepository.createJobExecution("JOB", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution(step.getName());

    step.execute(stepExecution);

    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());
    assertEquals(4, stepExecution.getReadCount());
    assertEquals(4, 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  w w  . ja  va  2 s  .  c om
    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.");
}