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

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

Introduction

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

Prototype

public String getStepName() 

Source Link

Usage

From source file:org.springframework.batch.core.job.flow.support.SimpleFlow.java

protected boolean isFlowContinued(State state, FlowExecutionStatus status, StepExecution stepExecution) {
    boolean continued = true;

    continued = state != null && status != FlowExecutionStatus.STOPPED;

    if (stepExecution != null) {
        Boolean reRun = (Boolean) stepExecution.getExecutionContext().get("batch.restart");
        Boolean executed = (Boolean) stepExecution.getExecutionContext().get("batch.executed");

        if ((executed == null || !executed) && reRun != null && reRun && status == FlowExecutionStatus.STOPPED
                && !state.getName().endsWith(stepExecution.getStepName())) {
            continued = true;//from  w  w w .jav  a 2 s  .co m
        }
    }

    return continued;
}

From source file:org.springframework.batch.core.job.flow.support.SimpleFlow.java

private boolean stateNameEndsWithStepName(State state, StepExecution stepExecution) {
    return !(stepExecution == null || state == null) && !state.getName().endsWith(stepExecution.getStepName());
}

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./*ww  w . ja v a  2  s  .com*/
 * @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.SimpleJobOperator.java

@Override
@Transactional/*from w w  w  .  j  av a2  s . co  m*/
public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException {

    JobExecution jobExecution = findExecutionById(executionId);
    // Indicate the execution should be stopped by setting it's status to
    // 'STOPPING'. It is assumed that
    // the step implementation will check this status at chunk boundaries.
    BatchStatus status = jobExecution.getStatus();
    if (!(status == BatchStatus.STARTED || status == BatchStatus.STARTING)) {
        throw new JobExecutionNotRunningException(
                "JobExecution must be running so that it can be stopped: " + jobExecution);
    }
    jobExecution.setStatus(BatchStatus.STOPPING);
    jobRepository.update(jobExecution);

    try {
        Job job = jobRegistry.getJob(jobExecution.getJobInstance().getJobName());
        if (job instanceof StepLocator) {//can only process as StepLocator is the only way to get the step object
            //get the current stepExecution
            for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
                if (stepExecution.getStatus().isRunning()) {
                    try {
                        //have the step execution that's running -> need to 'stop' it
                        Step step = ((StepLocator) job).getStep(stepExecution.getStepName());
                        if (step instanceof TaskletStep) {
                            Tasklet tasklet = ((TaskletStep) step).getTasklet();
                            if (tasklet instanceof StoppableTasklet) {
                                StepSynchronizationManager.register(stepExecution);
                                ((StoppableTasklet) tasklet).stop();
                                StepSynchronizationManager.release();
                            }
                        }
                    } catch (NoSuchStepException e) {
                        logger.warn("Step not found", e);
                    }
                }
            }
        }
    } catch (NoSuchJobException e) {
        logger.warn("Cannot find Job object", e);
    }

    return true;
}

From source file:org.springframework.batch.core.repository.dao.JdbcStepExecutionDao.java

private List<Object[]> buildStepExecutionParameters(StepExecution stepExecution) {
    Assert.isNull(stepExecution.getId(),
            "to-be-saved (not updated) StepExecution can't already have an id assigned");
    Assert.isNull(stepExecution.getVersion(),
            "to-be-saved (not updated) StepExecution can't already have a version assigned");
    validateStepExecution(stepExecution);
    stepExecution.setId(stepExecutionIncrementer.nextLongValue());
    stepExecution.incrementVersion(); //Should be 0
    List<Object[]> parameters = new ArrayList<Object[]>();
    String exitDescription = truncateExitDescription(stepExecution.getExitStatus().getExitDescription());
    Object[] parameterValues = new Object[] { stepExecution.getId(), stepExecution.getVersion(),
            stepExecution.getStepName(), stepExecution.getJobExecutionId(), stepExecution.getStartTime(),
            stepExecution.getEndTime(), stepExecution.getStatus().toString(), stepExecution.getCommitCount(),
            stepExecution.getReadCount(), stepExecution.getFilterCount(), stepExecution.getWriteCount(),
            stepExecution.getExitStatus().getExitCode(), exitDescription, stepExecution.getReadSkipCount(),
            stepExecution.getWriteSkipCount(), stepExecution.getProcessSkipCount(),
            stepExecution.getRollbackCount(), stepExecution.getLastUpdated() };
    Integer[] parameterTypes = new Integer[] { Types.BIGINT, Types.INTEGER, Types.VARCHAR, Types.BIGINT,
            Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.INTEGER, Types.TIMESTAMP };
    parameters.add(0, Arrays.copyOf(parameterValues, parameterValues.length));
    parameters.add(1, Arrays.copyOf(parameterTypes, parameterTypes.length));
    return parameters;
}

From source file:org.springframework.batch.core.repository.dao.JdbcStepExecutionDao.java

/**
 * Validate StepExecution. At a minimum, JobId, StartTime, and Status cannot
 * be null. EndTime can be null for an unfinished job.
 *
 * @throws IllegalArgumentException/*from  w w w  . j a va2 s.  com*/
 */
private void validateStepExecution(StepExecution stepExecution) {
    Assert.notNull(stepExecution);
    Assert.notNull(stepExecution.getStepName(), "StepExecution step name cannot be null.");
    Assert.notNull(stepExecution.getStartTime(), "StepExecution start time cannot be null.");
    Assert.notNull(stepExecution.getStatus(), "StepExecution status cannot be null.");
}

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

private void validateStepExecution(StepExecution stepExecution) {
    Assert.notNull(stepExecution, "StepExecution cannot be null.");
    Assert.notNull(stepExecution.getStepName(), "StepExecution's step name cannot be null.");
    Assert.notNull(stepExecution.getJobExecutionId(), "StepExecution must belong to persisted JobExecution");
}

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

@Override
public StepExecution getLastStepExecution(JobInstance jobInstance, String stepName) {
    List<JobExecution> jobExecutions = jobExecutionDao.findJobExecutions(jobInstance);
    List<StepExecution> stepExecutions = new ArrayList<StepExecution>(jobExecutions.size());

    for (JobExecution jobExecution : jobExecutions) {
        stepExecutionDao.addStepExecutions(jobExecution);
        for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
            if (stepName.equals(stepExecution.getStepName())) {
                stepExecutions.add(stepExecution);
            }//from   www.  ja  va 2s.co m
        }
    }

    StepExecution latest = null;
    for (StepExecution stepExecution : stepExecutions) {
        if (latest == null) {
            latest = stepExecution;
        }
        if (latest.getStartTime().getTime() < stepExecution.getStartTime().getTime()) {
            latest = stepExecution;
        }
    }

    if (latest != null) {
        ExecutionContext stepExecutionContext = ecDao.getExecutionContext(latest);
        latest.setExecutionContext(stepExecutionContext);
        ExecutionContext jobExecutionContext = ecDao.getExecutionContext(latest.getJobExecution());
        latest.getJobExecution().setExecutionContext(jobExecutionContext);
    }

    return latest;
}

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

/**
 * @return number of executions of the step within given job instance
 *//*ww  w. j  av a 2 s.c o  m*/
@Override
public int getStepExecutionCount(JobInstance jobInstance, String stepName) {
    int count = 0;
    List<JobExecution> jobExecutions = jobExecutionDao.findJobExecutions(jobInstance);
    for (JobExecution jobExecution : jobExecutions) {
        stepExecutionDao.addStepExecutions(jobExecution);
        for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
            if (stepName.equals(stepExecution.getStepName())) {
                count++;
            }
        }
    }
    return count;
}

From source file:org.springframework.batch.core.test.football.FootballJobIntegrationTests.java

@Test
public void testLaunchJob() throws Exception {
    JobExecution execution = jobLauncher.run(job,
            new JobParametersBuilder().addLong("commit.interval", 10L).toJobParameters());
    assertEquals(BatchStatus.COMPLETED, execution.getStatus());
    for (StepExecution stepExecution : execution.getStepExecutions()) {
        logger.info("Processed: " + stepExecution);
        if (stepExecution.getStepName().equals("playerload")) {
            // The effect of the retries
            assertEquals(new Double(Math.ceil(stepExecution.getReadCount() / 10. + 1)).intValue(),
                    stepExecution.getCommitCount());
        }/*from  w w  w  .j  a  va  2 s  .  c o  m*/
    }
}