Example usage for org.springframework.batch.core JobExecution createStepExecution

List of usage examples for org.springframework.batch.core JobExecution createStepExecution

Introduction

In this page you can find the example usage for org.springframework.batch.core JobExecution createStepExecution.

Prototype

public StepExecution createStepExecution(String stepName) 

Source Link

Document

Register a step execution with the current job execution.

Usage

From source file:org.springframework.cloud.dataflow.server.support.StepExecutionJacksonMixInTests.java

private StepExecution getStepExecution() {
    JobExecution jobExecution = new JobExecution(1L, null, "hi");
    final StepExecution stepExecution = new StepExecution("step1", jobExecution);
    jobExecution.createStepExecution("step1");
    final ExecutionContext executionContext = stepExecution.getExecutionContext();

    executionContext.putInt("counter", 1234);
    executionContext.putDouble("myDouble", 1.123456d);
    executionContext.putLong("Josh", 4444444444L);
    executionContext.putString("awesomeString", "Yep");
    executionContext.put("hello", "world");
    executionContext.put("counter2", 9999);

    return stepExecution;
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsUserWriterTest.java

public StepExecution getStepExecution() {

    final Map<String, JobParameter> map = new HashMap<String, JobParameter>();
    final JobParameters jobParams = new JobParameters(map);
    final JobExecution exec = MetaDataInstanceFactory.createJobExecution("testJob", 1L, 1L, jobParams);

    exec.getExecutionContext().put("mantis.loop.project_id", BigInteger.ONE);

    final StepExecution stepExecution = exec.createStepExecution("testStep");
    return stepExecution;
}

From source file:com.xchanging.support.batch.admin.service.SimpleJobService.java

public Collection<StepExecution> getStepExecutions(Long jobExecutionId) throws NoSuchJobExecutionException {

    JobExecution jobExecution = jobExecutionDao.getJobExecution(jobExecutionId);
    if (jobExecution == null) {
        throw new NoSuchJobExecutionException("No JobExecution with id=" + jobExecutionId);
    }/* w w w  .  j  a  v  a2 s.  c  o m*/

    stepExecutionDao.addStepExecutions(jobExecution);

    String jobName = jobExecution.getJobInstance() == null ? null : jobExecution.getJobInstance().getJobName();
    Collection<String> missingStepNames = new LinkedHashSet<String>();

    if (jobName != null) {
        missingStepNames.addAll(stepExecutionDao.findStepNamesForJobExecution(jobName, "*:partition*"));
        logger.debug("Found step executions in repository: " + missingStepNames);
    }

    Job job = null;
    try {
        job = jobLocator.getJob(jobName);
    } catch (NoSuchJobException e) {
        // expected
    }
    if (job instanceof StepLocator) {
        Collection<String> stepNames = ((StepLocator) job).getStepNames();
        missingStepNames.addAll(stepNames);
        logger.debug("Added step executions from job: " + missingStepNames);
    }

    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
        String stepName = stepExecution.getStepName();
        if (missingStepNames.contains(stepName)) {
            missingStepNames.remove(stepName);
        }
        logger.debug("Removed step executions from job execution: " + missingStepNames);
    }

    for (String stepName : missingStepNames) {
        StepExecution stepExecution = jobExecution.createStepExecution(stepName);
        stepExecution.setStatus(BatchStatus.UNKNOWN);
    }

    return jobExecution.getStepExecutions();

}

From source file:admin.service.SimpleJobService.java

@Override
public Collection<StepExecution> getStepExecutions(Long jobExecutionId) throws NoSuchJobExecutionException {

    JobExecution jobExecution = jobExecutionDao.getJobExecution(jobExecutionId);
    if (jobExecution == null) {
        throw new NoSuchJobExecutionException("No JobExecution with id=" + jobExecutionId);
    }//from   www .  j a  va  2 s.  c om

    stepExecutionDao.addStepExecutions(jobExecution);

    String jobName = jobExecution.getJobInstance() == null
            ? jobInstanceDao.getJobInstance(jobExecution).getJobName()
            : jobExecution.getJobInstance().getJobName();
    Collection<String> missingStepNames = new LinkedHashSet<String>();

    if (jobName != null) {
        missingStepNames.addAll(stepExecutionDao.findStepNamesForJobExecution(jobName, "*:partition*"));
        logger.debug("Found step executions in repository: " + missingStepNames);
    }

    Job job = null;
    try {
        job = jobLocator.getJob(jobName);
    } catch (NoSuchJobException e) {
        // expected
    }
    if (job instanceof StepLocator) {
        Collection<String> stepNames = ((StepLocator) job).getStepNames();
        missingStepNames.addAll(stepNames);
        logger.debug("Added step executions from job: " + missingStepNames);
    }

    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
        String stepName = stepExecution.getStepName();
        if (missingStepNames.contains(stepName)) {
            missingStepNames.remove(stepName);
        }
        logger.debug("Removed step executions from job execution: " + missingStepNames);
    }

    for (String stepName : missingStepNames) {
        StepExecution stepExecution = jobExecution.createStepExecution(stepName);
        stepExecution.setStatus(BatchStatus.UNKNOWN);
    }

    return jobExecution.getStepExecutions();

}

From source file:org.springframework.batch.core.explore.support.SimpleJobExplorerIntegrationTests.java

@Test
public void testGetStepExecution() throws JobExecutionAlreadyRunningException, JobRestartException,
        JobInstanceAlreadyCompleteException, JobInterruptedException, UnexpectedJobExecutionException {

    // Prepare the jobRepository for the test
    JobExecution jobExecution = jobRepository.createJobExecution("myJob", new JobParameters());
    StepExecution stepExecution = jobExecution.createStepExecution("flowStep");
    jobRepository.add(stepExecution);/*from   w  w  w .  j a v a 2s . c  om*/

    // Executed on the remote end in remote partitioning use case
    StepExecution jobExplorerStepExecution = jobExplorer.getStepExecution(jobExecution.getId(),
            stepExecution.getId());
    flowStep.execute(jobExplorerStepExecution);

    assertEquals(BatchStatus.COMPLETED, jobExplorerStepExecution.getStatus());
}

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.");
    }/*from   ww w  .  j  av a  2s .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.step.item.FaultTolerantStepFactoryBeanUnexpectedRollbackTests.java

@Test
@Ignore //FIXME//w w w  .java 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.AsyncTaskletStepTests.java

/**
 * StepExecution should be updated after every chunk commit.
 *///from ww  w  .  j av a  2  s  .c om
@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 ww . ja v a2 s .co 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.
 *//*  w  w  w .ja  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());

}