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

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

Introduction

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

Prototype

public Long getId() 

Source Link

Usage

From source file:org.springframework.batch.core.repository.support.SimpleJobRepository.java

@Override
public void updateExecutionContext(StepExecution stepExecution) {
    validateStepExecution(stepExecution);
    Assert.notNull(stepExecution.getId(), "StepExecution must already be saved (have an id assigned)");
    ecDao.updateExecutionContext(stepExecution);
}

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)})./*from w ww  . ja v  a  2  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.FaultTolerantStepFactoryBeanTests.java

private void assertStepExecutionsAreEqual(StepExecution expected, StepExecution actual) {
    assertEquals(expected.getId(), actual.getId());
    assertEquals(expected.getStartTime(), actual.getStartTime());
    assertEquals(expected.getEndTime(), actual.getEndTime());
    assertEquals(expected.getSkipCount(), actual.getSkipCount());
    assertEquals(expected.getCommitCount(), actual.getCommitCount());
    assertEquals(expected.getReadCount(), actual.getReadCount());
    assertEquals(expected.getWriteCount(), actual.getWriteCount());
    assertEquals(expected.getFilterCount(), actual.getFilterCount());
    assertEquals(expected.getWriteSkipCount(), actual.getWriteSkipCount());
    assertEquals(expected.getReadSkipCount(), actual.getReadSkipCount());
    assertEquals(expected.getProcessSkipCount(), actual.getProcessSkipCount());
    assertEquals(expected.getRollbackCount(), actual.getRollbackCount());
    assertEquals(expected.getExitStatus(), actual.getExitStatus());
    assertEquals(expected.getLastUpdated(), actual.getLastUpdated());
    assertEquals(expected.getExitStatus(), actual.getExitStatus());
    assertEquals(expected.getJobExecutionId(), actual.getJobExecutionId());
}

From source file:org.springframework.batch.integration.partition.JmsIntegrationTests.java

@Test
public void testLaunchJob() throws Exception {
    int before = jobExplorer.getJobInstances(job.getName(), 0, 100).size();
    assertNotNull(jobLauncher.run(job, new JobParameters()));
    List<JobInstance> jobInstances = jobExplorer.getJobInstances(job.getName(), 0, 100);
    int after = jobInstances.size();
    assertEquals(1, after - before);//from w  ww  .j a  va  2  s .c om
    JobExecution jobExecution = jobExplorer.getJobExecutions(jobInstances.get(jobInstances.size() - 1)).get(0);
    assertEquals(jobExecution.getExitStatus().getExitDescription(), BatchStatus.COMPLETED,
            jobExecution.getStatus());
    assertEquals(3, jobExecution.getStepExecutions().size());
    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
        // BATCH-1703: we are using a map dao so the step executions in the job execution are old and we need to
        // pull them back out of the repository...
        stepExecution = jobExplorer.getStepExecution(jobExecution.getId(), stepExecution.getId());
        logger.debug("" + stepExecution);
        assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    }
}

From source file:org.springframework.cloud.task.batch.partition.DeployerPartitionHandler.java

private void launchWorker(StepExecution workerStepExecution) {
    //TODO: Refactor these to be passed as command line args once SCD-20 is complete
    // https://github.com/spring-cloud/spring-cloud-deployer/issues/20
    Map<String, String> arguments = getArguments(this.taskExecution.getArguments());
    arguments.put(SPRING_CLOUD_TASK_JOB_EXECUTION_ID,
            String.valueOf(workerStepExecution.getJobExecution().getId()));
    arguments.put(SPRING_CLOUD_TASK_STEP_EXECUTION_ID, String.valueOf(workerStepExecution.getId()));
    arguments.put(SPRING_CLOUD_TASK_STEP_NAME, this.stepName);

    AppDefinition definition = new AppDefinition(String.format("%s:%s:%s", taskExecution.getTaskName(),
            workerStepExecution.getJobExecution().getJobInstance().getJobName(),
            workerStepExecution.getStepName()), arguments);

    Map<String, String> environmentProperties = new HashMap<>(this.environmentProperties.size());
    environmentProperties.putAll(getCurrentEnvironmentProperties());
    environmentProperties.putAll(this.environmentProperties);

    AppDeploymentRequest request = new AppDeploymentRequest(definition, this.resource, environmentProperties);

    taskLauncher.launch(request);//from w w w. j  av a2  s.c  o  m
}

From source file:org.springframework.cloud.task.batch.partition.DeployerPartitionHandler.java

private Collection<StepExecution> pollReplies(final StepExecution masterStepExecution,
        final Set<StepExecution> executed, final Set<StepExecution> candidates, final int size)
        throws Exception {

    final Collection<StepExecution> result = new ArrayList<>(executed.size());

    Callable<Collection<StepExecution>> callback = new Callable<Collection<StepExecution>>() {
        @Override//from w  ww  . j av  a2 s .co m
        public Collection<StepExecution> call() throws Exception {
            Set<StepExecution> newExecuted = new HashSet<>();

            for (StepExecution curStepExecution : executed) {
                if (!result.contains(curStepExecution)) {
                    StepExecution partitionStepExecution = jobExplorer.getStepExecution(
                            masterStepExecution.getJobExecutionId(), curStepExecution.getId());

                    if (isComplete(partitionStepExecution.getStatus())) {
                        result.add(partitionStepExecution);
                        currentWorkers--;

                        if (!candidates.isEmpty()) {

                            launchWorkers(candidates, newExecuted);
                            candidates.removeAll(newExecuted);
                        }
                    }
                }
            }

            executed.addAll(newExecuted);

            if (result.size() == size) {
                return result;
            } else {
                return null;
            }
        }
    };

    Poller<Collection<StepExecution>> poller = new DirectPoller<>(this.pollInterval);
    Future<Collection<StepExecution>> resultsFuture = poller.poll(callback);

    if (timeout >= 0) {
        return resultsFuture.get(timeout, TimeUnit.MILLISECONDS);
    } else {
        return resultsFuture.get();
    }
}

From source file:org.springframework.yarn.batch.am.AbstractBatchAppmaster.java

@Override
public ContainerLaunchContext preLaunch(Container container, ContainerLaunchContext context) {
    AppmasterService service = getAppmasterService();

    if (log.isDebugEnabled()) {
        log.debug("Intercept launch context: " + context);
    }//from ww w  . j av a 2s. c  o m

    StepExecution stepExecution = containerToStepMap.get(container.getId());
    String jobName = remoteStepNames.get(stepExecution);

    if (service != null) {
        int port = service.getPort();
        String address = service.getHost();
        Map<String, String> env = new HashMap<String, String>(context.getEnvironment());
        env.put(YarnSystemConstants.FS_ADDRESS,
                getConfiguration().get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY));
        env.put(YarnSystemConstants.AMSERVICE_PORT, Integer.toString(port));
        env.put(YarnSystemConstants.AMSERVICE_HOST, address);
        env.put(YarnSystemConstants.AMSERVICE_BATCH_STEPNAME, jobName);
        env.put(YarnSystemConstants.AMSERVICE_BATCH_STEPNAME, jobName);
        env.put(YarnSystemConstants.AMSERVICE_BATCH_STEPEXECUTIONNAME, stepExecution.getStepName());
        env.put(YarnSystemConstants.AMSERVICE_BATCH_JOBEXECUTIONID,
                Long.toString(stepExecution.getJobExecutionId()));
        env.put(YarnSystemConstants.AMSERVICE_BATCH_STEPEXECUTIONID, Long.toString(stepExecution.getId()));
        context.setEnvironment(env);
        return context;
    } else {
        return context;
    }
}

From source file:org.springframework.yarn.batch.repository.JobRepositoryRemoteService.java

/**
 * Handles saving a step execution.// www .  ja  v a2  s  . co  m
 *
 * @param request the {@link SaveStepExecutionReq}
 * @return the {@link SaveStepExecutionRes}
 */
private SaveStepExecutionRes handleSaveStepExecution(SaveStepExecutionReq request) {
    SaveStepExecutionRes response = null;
    try {
        StepExecution stepExecution = JobRepositoryRpcFactory.convertStepExecutionType(request.stepExecution);
        stepExecutionDao.saveStepExecution(stepExecution);
        response = new SaveStepExecutionRes(stepExecution.getId(), stepExecution.getVersion());
    } catch (Exception e) {
        log.error("error handling command", e);
    }
    return response;
}

From source file:org.springframework.yarn.batch.repository.JobRepositoryRemoteService.java

/**
 * Handles updating a step execution./*from ww  w .  j  a v a2 s  .  com*/
 *
 * @param request the {@link UpdateStepExecutionReq}
 * @return the {@link UpdateStepExecutionRes}
 */
private UpdateStepExecutionRes handleUpdateStepExecution(UpdateStepExecutionReq request) {
    UpdateStepExecutionRes response = null;
    try {
        StepExecution stepExecution = JobRepositoryRpcFactory.convertStepExecutionType(request.stepExecution);
        stepExecutionDao.updateStepExecution(stepExecution);
        response = new UpdateStepExecutionRes(stepExecution.getId(), stepExecution.getVersion());
    } catch (Exception e) {
        log.error("error handling command", e);
    }
    return response;
}

From source file:org.springframework.yarn.batch.repository.JobRepositoryService.java

private BaseResponseObject handleAddWithStepExecutionReq(AddWithStepExecutionReq request) {
    AddWithStepExecutionRes response = null;
    StepExecution stepExecution = JobRepositoryRpcFactory.convertStepExecutionType(request.stepExecution);
    jobRepository.add(stepExecution);/* w ww . j ava2  s. com*/
    response = new AddWithStepExecutionRes();
    response.id = stepExecution.getId();
    response.version = stepExecution.getVersion();
    return response;
}