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

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

Introduction

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

Prototype

public JobExecution getJobExecution() 

Source Link

Document

Accessor for the execution context information of the enclosing job.

Usage

From source file:uk.ac.ebi.intact.editor.batch.admin.MailNotifierStepExecutionListener.java

public ExitStatus afterStep(StepExecution stepExecution) {

    SimpleMailMessage message = newSimpleMessage();
    message.setSubject("[Editor_import] Finished step: " + stepExecution.getStepName() + " Exit status: "
            + stepExecution.getExitStatus().getExitCode());
    message.setText(stepExecution.toString() + "\n" + stepExecution.getExecutionContext());
    message.setText(stepExecution.toString() + "\n" + stepExecution.getSummary() + "\n"
            + stepExecution.getJobExecution());
    message.setTo(stepExecution.getJobParameters().getString("email.recipient"));

    try {/*from  www .jav a2 s . c o m*/
        mailSender.send(message);
    } catch (MailException e) {
        log.error("Impossible to send e-mail", e);
    }

    return stepExecution.getExitStatus();
}

From source file:org.seedstack.monitoring.batch.internal.rest.stepexecution.StepExecutionRepresentation.java

/**
 * Instantiates a new step execution representation.
 *
 * @param stepExecution the step execution
 * @param timeZone      the time zone/*from   w  w w  .  j  ava  2s.c  om*/
 */
public StepExecutionRepresentation(StepExecution stepExecution, TimeZone timeZone) {

    this.setStepExecutionDetailsRepresentation(new StepExecutionDetailsRepresentation(stepExecution));
    this.id = stepExecution.getId();
    this.name = stepExecution.getStepName();
    this.jobName = stepExecution.getJobExecution() == null
            || stepExecution.getJobExecution().getJobInstance() == null ? "?"
                    : stepExecution.getJobExecution().getJobInstance().getJobName();
    this.jobExecutionId = stepExecution.getJobExecutionId();
    // Duration is always in GMT
    durationFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    timeFormat.setTimeZone(timeZone);
    dateFormat.setTimeZone(timeZone);
    if (stepExecution.getStartTime() != null) {
        this.startDate = dateFormat.format(stepExecution.getStartTime());
        this.startTime = timeFormat.format(stepExecution.getStartTime());
        Date endTime = stepExecution.getEndTime() != null ? stepExecution.getEndTime() : new Date();

        this.durationMillis = endTime.getTime() - stepExecution.getStartTime().getTime();
        this.duration = durationFormat.format(new Date(durationMillis));
    }
    if (stepExecution.getEndTime() != null) {
        this.endTime = timeFormat.format(stepExecution.getEndTime());
    }

}

From source file:org.springframework.batch.admin.web.StepExecutionController.java

@RequestMapping(value = "/jobs/executions/{jobExecutionId}/steps/{stepExecutionId}/progress", method = RequestMethod.GET)
public String history(Model model, @PathVariable Long jobExecutionId, @PathVariable Long stepExecutionId,
        @ModelAttribute("date") Date date, Errors errors) {

    try {/*  w  w w . j a v  a2  s . c om*/
        StepExecution stepExecution = jobService.getStepExecution(jobExecutionId, stepExecutionId);
        model.addAttribute(new StepExecutionInfo(stepExecution, timeZone));
        String stepName = stepExecution.getStepName();
        if (stepName.contains(":partition")) {
            // assume we want to compare all partitions
            stepName = stepName.replaceAll("(:partition).*", "$1*");
        }
        String jobName = stepExecution.getJobExecution().getJobInstance().getJobName();
        StepExecutionHistory stepExecutionHistory = computeHistory(jobName, stepName);
        model.addAttribute(stepExecutionHistory);
        model.addAttribute(new StepExecutionProgress(stepExecution, stepExecutionHistory));
    } catch (NoSuchStepExecutionException e) {
        errors.reject("no.such.step.execution", new Object[] { stepExecutionId },
                "There is no such step execution (" + stepExecutionId + ")");
    } catch (NoSuchJobExecutionException e) {
        errors.reject("no.such.job.execution", new Object[] { jobExecutionId },
                "There is no such job execution (" + jobExecutionId + ")");
    }

    return "jobs/executions/step/progress";

}

From source file:org.trpr.platform.batch.impl.spring.admin.repository.MapStepExecutionDao.java

@Override
public void updateStepExecution(StepExecution stepExecution) {

    Assert.notNull(stepExecution.getJobExecutionId());

    //If the job execution data doesn't exist, can't update   
    if (!executionsByJobExecutionId.containsKey(stepExecution.getJobExecutionId())) {
        return;/*from w  ww.ja  va  2  s . c o  m*/
    }

    Map<Long, StepExecution> executions = executionsByJobExecutionId.get(stepExecution.getJobExecutionId());
    Assert.notNull(executions, "step executions for given job execution are expected to be already saved");

    final StepExecution persistedExecution = executionsByStepExecutionId.get(stepExecution.getId());
    Assert.notNull(persistedExecution, "step execution is expected to be already saved");

    synchronized (stepExecution) {
        if (!persistedExecution.getVersion().equals(stepExecution.getVersion())) {
            throw new OptimisticLockingFailureException("Attempt to update step execution id="
                    + stepExecution.getId() + " with wrong version (" + stepExecution.getVersion()
                    + "), where current version is " + persistedExecution.getVersion());
        }

        stepExecution.incrementVersion();
        StepExecution copy = new StepExecution(stepExecution.getStepName(), stepExecution.getJobExecution());
        copy(stepExecution, copy);
        executions.put(stepExecution.getId(), copy);
        executionsByStepExecutionId.put(stepExecution.getId(), copy);
    }
}

From source file:org.jasig.ssp.util.importer.job.listener.ParsingListener.java

@SuppressWarnings("unchecked")
@Override//from   ww w.ja va2  s. c  o m
@AfterStep
public ExitStatus afterStep(StepExecution arg0) {
    // The "fileName" context property has been normalized so the file separator is
    // not platform-specific
    String fileSeparatorRegex = "/";
    String fileName = this.getStepExecution().getExecutionContext().getString("fileName");
    String[] split = fileName.split(fileSeparatorRegex);
    String pathname = split[split.length - 1];
    String[] split1 = pathname.split("\\.");
    String currentEntity = split1[0];

    if (currentEntity != null) {
        Map<String, ReportEntry> report = (Map<String, ReportEntry>) this.getStepExecution().getJobExecution()
                .getExecutionContext().get("report");
        if (report == null) {
            report = new HashMap<String, ReportEntry>();
        }
        ReportEntry currentEntry = report.get(currentEntity);
        if (currentEntry != null) {
            currentEntry.setTableName(currentEntity);
            currentEntry.setNumberParsed(this.getStepExecution().getReadCount());
            currentEntry.setNumberSkippedOnParse(this.getStepExecution().getProcessSkipCount());
        } else {
            currentEntry = new ReportEntry();
            currentEntry.setTableName(currentEntity);
            currentEntry.setNumberParsed(this.getStepExecution().getReadCount());
            currentEntry.setNumberSkippedOnParse(this.getStepExecution().getProcessSkipCount());
        }
        report.put(currentEntity, currentEntry);
        arg0.getJobExecution().getExecutionContext().put("report", report);
    }

    return ExitStatus.COMPLETED;
}

From source file:org.springframework.batch.core.partition.gemfire.GemfirePartitionFunction.java

private StepExecution execute(StepExecution stepExecution) {
    try {/*  ww  w . java2s .c o m*/
        step.execute(stepExecution);
    } catch (JobInterruptedException e) {
        stepExecution.getJobExecution().setStatus(BatchStatus.STOPPING);
        throw new UnexpectedJobExecutionException("TODO: this should result in a stop", e);
    }
    return stepExecution;
}

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  w w w.j av a  2  s.c o  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

/**
 * Check to determine whether or not the JobExecution that is the parent of
 * the provided StepExecution has been interrupted. If, after synchronizing
 * the status with the database, the status has been updated to STOPPING,
 * then the job has been interrupted.//from w w  w .jav a 2 s . co  m
 *
 * @param stepExecution
 */
private void checkForInterruption(StepExecution stepExecution) {
    JobExecution jobExecution = stepExecution.getJobExecution();
    jobExecutionDao.synchronizeStatus(jobExecution);
    if (jobExecution.isStopping()) {
        logger.info("Parent JobExecution is stopped, so passing message on to StepExecution");
        stepExecution.setTerminateOnly();
    }
}

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  a  2 s .c om*/
 */
@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.integration.x.IncrementalColumnRangePartitioner.java

@Override
public void beforeStep(StepExecution stepExecution) {
    if (StringUtils.hasText(checkColumn)) {

        if (overrideValue != null && overrideValue >= 0) {
            this.incrementalMin = overrideValue;
        } else {/*from w w w  . j av  a 2  s  . c o  m*/
            String jobName = stepExecution.getJobExecution().getJobInstance().getJobName();

            // Get the last jobInstance...not the current one
            List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 1, 1);

            if (jobInstances.size() > 0) {
                JobInstance lastInstance = jobInstances.get(jobInstances.size() - 1);

                List<JobExecution> executions = jobExplorer.getJobExecutions(lastInstance);

                JobExecution lastExecution = executions.get(0);

                for (JobExecution execution : executions) {
                    if (lastExecution.getEndTime().getTime() < execution.getEndTime().getTime()) {
                        lastExecution = execution;
                    }
                }

                if (lastExecution.getExecutionContext().containsKey(BATCH_INCREMENTAL_MAX_ID)) {
                    this.incrementalMin = lastExecution.getExecutionContext().getLong(BATCH_INCREMENTAL_MAX_ID);
                } else {
                    this.incrementalMin = Long.MIN_VALUE;
                }
            } else {
                this.incrementalMin = Long.MIN_VALUE;
            }
        }

        long newMin = jdbcTemplate.queryForObject(String.format("select max(%s) from %s", checkColumn, table),
                Integer.class);

        stepExecution.getExecutionContext().put(BATCH_INCREMENTAL_MAX_ID, newMin);
    }

    if (StringUtils.hasText(column) && StringUtils.hasText(table)) {
        if (StringUtils.hasText(checkColumn)) {
            Long minResult = jdbcTemplate.queryForObject("SELECT MIN(" + column + ") from " + table + " where "
                    + checkColumn + " > " + this.incrementalMin, Long.class);
            Long maxResult = jdbcTemplate.queryForObject("SELECT MAX(" + column + ") from " + table + " where "
                    + checkColumn + " > " + this.incrementalMin, Long.class);
            this.partitionMin = minResult != null ? minResult : Long.MIN_VALUE;
            this.partitionMax = maxResult != null ? maxResult : Long.MAX_VALUE;
        } else {
            Long minResult = jdbcTemplate.queryForObject("SELECT MIN(" + column + ") from " + table,
                    Long.class);
            Long maxResult = jdbcTemplate.queryForObject("SELECT MAX(" + column + ") from " + table,
                    Long.class);
            this.partitionMin = minResult != null ? minResult : Long.MIN_VALUE;
            this.partitionMax = maxResult != null ? maxResult : Long.MAX_VALUE;
        }
    }
}