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

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

Introduction

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

Prototype

public ExecutionContext getExecutionContext() 

Source Link

Document

Returns the ExecutionContext for this execution.

Usage

From source file:uk.ac.kcl.listeners.JobCompleteNotificationListener.java

@Override
public synchronized void afterJob(JobExecution jobExecution) {
    if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
        if (columnRangePartitioner.isFirstRun()) {
            columnRangePartitioner.setFirstRun(false);
        }/*from   w  w w . j  av  a2  s  . c  om*/
        log.info("!!! JOB FINISHED! promoting last good record date to JobExecutionContext");
        jobExecution.getExecutionContext().put("last_successful_timestamp_from_this_job", timeOfNextJob);
        jobRepository.updateExecutionContext(jobExecution);
    }

    if (esRestService != null) {
        // Workaround to close ElasticSearch REST properly (the job was stuck before this change)
        try {
            esRestService.destroy();
        } catch (IOException e) {
            log.warn("IOException when destroying ElasticSearch REST service");
        }
    }
}

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

@RequestMapping(value = "/jobs/executions/{jobExecutionId}/execution-context", method = RequestMethod.GET)
public String getExecutionContext(Model model, @PathVariable Long jobExecutionId,
        @ModelAttribute("date") Date date, Errors errors) {
    try {/*from  w  ww .ja v  a 2 s.c o m*/
        JobExecution jobExecution = jobService.getJobExecution(jobExecutionId);
        Map<String, Object> executionMap = new HashMap<String, Object>();

        for (Map.Entry<String, Object> entry : jobExecution.getExecutionContext().entrySet()) {
            executionMap.put(entry.getKey(), entry.getValue());
        }

        model.addAttribute("jobExecutionContext", objectMapper.writeValueAsString(executionMap));
        model.addAttribute("jobExecutionId", jobExecutionId);
    } catch (NoSuchJobExecutionException e) {
        errors.reject("no.such.job.execution", new Object[] { jobExecutionId },
                "There is no such job execution (" + jobExecutionId + ")");
    } catch (IOException e) {
        errors.reject("serialization.error", new Object[] { jobExecutionId },
                "Error serializing execution context for job execution (" + jobExecutionId + ")");
    }

    return "jobs/executions/execution-context";
}

From source file:be.ordina.springbatch.batch.listener.TrajectInformationJobExecutionListener.java

@Override
public void afterJob(JobExecution jobExecution) {
    if (jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) {
        int reads = jobExecution.getStepExecutions().stream().mapToInt(se -> se.getReadCount()).sum();
        int writes = jobExecution.getStepExecutions().stream().mapToInt(se -> se.getWriteCount()).sum();
        int skips = jobExecution.getStepExecutions().stream().mapToInt(se -> se.getSkipCount()).sum();
        System.out.println("BATCH COMPLETED WITH GREAT SUCCESS reads = [ " + reads + " ] writes = [ " + writes
                + " ] skips = [" + skips + "]");
        for (LicensePlateType licensePlateType : LicensePlateType.values()) {
            System.out.println(licensePlateType.name().toLowerCase() + " - "
                    + jobExecution.getExecutionContext().getInt(licensePlateType.name(), 0));
        }/*w ww .  j  a va 2 s . c  o  m*/
        System.out.println(
                "Total grave errors this batch : " + jobExecution.getExecutionContext().getInt("graveErrors"));
        System.out.println("Total money stolen from the honest speeder : "
                + jobExecution.getExecutionContext().getDouble("total") + "");
    } else {
        System.err.println("BATCH COMPLETED WITH STATUS " + jobExecution.getExitStatus().getExitCode());
    }
}

From source file:de.codecentric.batch.listener.ProtocolListener.java

public void afterJob(JobExecution jobExecution) {
    StringBuilder protocol = new StringBuilder();
    protocol.append("\n");
    protocol.append(createFilledLine('*'));
    protocol.append(createFilledLine('-'));
    protocol.append("Protocol for " + jobExecution.getJobInstance().getJobName() + " \n");
    protocol.append("  Started:      " + jobExecution.getStartTime() + "\n");
    protocol.append("  Finished:     " + jobExecution.getEndTime() + "\n");
    protocol.append("  Exit-Code:    " + jobExecution.getExitStatus().getExitCode() + "\n");
    protocol.append("  Exit-Descr:   " + jobExecution.getExitStatus().getExitDescription() + "\n");
    protocol.append("  Status:       " + jobExecution.getStatus() + "\n");
    protocol.append("  Content of Job-ExecutionContext:\n");
    for (Entry<String, Object> entry : jobExecution.getExecutionContext().entrySet()) {
        protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
    }/*w w w  . j  av a2 s  . co  m*/
    protocol.append("  Job-Parameter: \n");
    JobParameters jp = jobExecution.getJobParameters();
    for (Iterator<Entry<String, JobParameter>> iter = jp.getParameters().entrySet().iterator(); iter
            .hasNext();) {
        Entry<String, JobParameter> entry = iter.next();
        protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
    }
    protocol.append(createFilledLine('-'));
    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
        protocol.append("Step " + stepExecution.getStepName() + " \n");
        protocol.append("  ReadCount:    " + stepExecution.getReadCount() + "\n");
        protocol.append("  WriteCount:   " + stepExecution.getWriteCount() + "\n");
        protocol.append("  Commits:      " + stepExecution.getCommitCount() + "\n");
        protocol.append("  SkipCount:    " + stepExecution.getSkipCount() + "\n");
        protocol.append("  Rollbacks:    " + stepExecution.getRollbackCount() + "\n");
        protocol.append("  Filter:       " + stepExecution.getFilterCount() + "\n");
        protocol.append("  Content of Step-ExecutionContext:\n");
        for (Entry<String, Object> entry : stepExecution.getExecutionContext().entrySet()) {
            protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
        }
        protocol.append(createFilledLine('-'));
    }
    protocol.append(createFilledLine('*'));
    LOGGER.info(protocol.toString());
}

From source file:org.springframework.batch.admin.domain.JobExecutionInfoResource.java

public JobExecutionInfoResource(JobExecution jobExecution, TimeZone timeZone) {

    if (timeZone != null) {
        this.timeZone = timeZone;
    } else {//from  w ww . j a  va  2s. co m
        this.timeZone = TimeZone.getTimeZone("UTC");
    }

    this.executionId = jobExecution.getId();
    this.jobId = jobExecution.getJobId();
    this.stepExecutionCount = jobExecution.getStepExecutions().size();
    this.jobParameters = jobExecution.getJobParameters();
    this.status = jobExecution.getStatus();
    this.exitStatus = jobExecution.getExitStatus();
    this.jobConfigurationName = jobExecution.getJobConfigurationName();
    this.failureExceptions = jobExecution.getFailureExceptions();
    Map<String, Object> executionContextEntires = new HashMap<String, Object>(
            jobExecution.getExecutionContext().size());

    for (Map.Entry<String, Object> stringObjectEntry : jobExecution.getExecutionContext().entrySet()) {
        executionContextEntires.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
    }

    this.executionContext = executionContextEntires;

    this.version = jobExecution.getVersion();

    JobInstance jobInstance = jobExecution.getJobInstance();
    if (jobInstance != null) {
        this.jobName = jobInstance.getJobName();
        BatchStatus status = jobExecution.getStatus();
        this.restartable = status.isGreaterThan(BatchStatus.STOPPING)
                && status.isLessThan(BatchStatus.ABANDONED);
        this.abandonable = status.isGreaterThan(BatchStatus.STARTED) && status != BatchStatus.ABANDONED;
        this.stoppable = status.isLessThan(BatchStatus.STOPPING) && status != BatchStatus.COMPLETED;
    } else {
        this.jobName = "?";
    }

    this.dateFormat = this.dateFormat.withZone(DateTimeZone.forTimeZone(timeZone));

    this.createDate = dateFormat.print(jobExecution.getCreateTime().getTime());
    this.lastUpdated = dateFormat.print(jobExecution.getLastUpdated().getTime());

    if (jobExecution.getStartTime() != null) {
        this.startTime = dateFormat.print(jobExecution.getStartTime().getTime());
        this.endTime = dateFormat.print(jobExecution.getEndTime().getTime());
    }
}

From source file:org.jasig.ssp.util.importer.job.report.ReportGenerator.java

@SuppressWarnings("unchecked")
private String buildReport(JobExecution jobExecution) {
    StringBuffer emailMessage = new StringBuffer();
    String EOL = System.getProperty("line.separator");
    SimpleDateFormat dt = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
    long diff = jobExecution.getEndTime().getTime() - jobExecution.getCreateTime().getTime();//as given

    emailMessage.append("Start Time:    " + dt.format(jobExecution.getCreateTime()) + EOL);
    emailMessage.append("End Time:      " + dt.format(jobExecution.getEndTime()) + EOL);
    emailMessage.append("Duration:      " + DurationFormatUtils.formatDurationWords(diff, true, true) + " ("
            + DurationFormatUtils.formatDurationHMS(diff) + ")" + EOL);
    emailMessage.append("Job Id:        " + jobExecution.getJobId() + EOL);
    emailMessage.append("Job Paramters: " + jobExecution.getJobParameters() + EOL);
    emailMessage.append("Job Status:    " + jobExecution.getExitStatus().getExitCode() + EOL);

    emailMessage.append(EOL).append(EOL);

    emailMessage.append("Job Details: " + EOL);
    Map<String, ReportEntry> report = (Map<String, ReportEntry>) jobExecution.getExecutionContext()
            .get("report");
    if (report != null) {
        Set<Entry<String, ReportEntry>> entrySet = report.entrySet();
        for (Entry<String, ReportEntry> entry : entrySet) {
            emailMessage.append(entry.getValue().toString() + EOL);
        }//ww  w. j  a v  a2 s .  c  om
        if (entrySet.size() > 0)
            emailReport = true;
    } else {
        emailMessage.append("NO FILES PROCESSED." + EOL);
    }

    emailMessage.append(EOL).append(EOL);

    emailMessage.append("Errors: " + EOL);
    List<ErrorEntry> errors = (List<ErrorEntry>) jobExecution.getExecutionContext().get("errors");
    List<Throwable> failureExceptions = jobExecution.getAllFailureExceptions();
    if (errors != null) {
        for (ErrorEntry errorEntry : errors) {
            emailMessage.append(errorEntry.toString() + EOL);
            emailMessage.append(EOL);
        }
    } else if (failureExceptions == null || failureExceptions.size() == 0) {
        emailMessage.append("No Errors Found." + EOL);
    }

    if (failureExceptions != null) {
        for (Throwable failureException : failureExceptions) {
            if (ExceptionUtils.indexOfThrowable(failureException, PartialUploadGuardException.class) >= 0
                    || ExceptionUtils.indexOfThrowable(failureException, BeanCreationException.class) >= 0) {
                emailReport = true;
                logger.info("emailReport:" + emailReport);
            }
            logger.info("failureException:" + failureException.getClass().getName());
            emailMessage.append(failureException.getMessage() + EOL);
        }
    }

    String validations = (String) jobExecution.getExecutionContext().get("databaseValidations");
    if (validations != null) {
        emailMessage.append("Database Validations:" + EOL + validations);
    }

    logger.info(emailMessage.toString());
    return emailMessage.toString();
}

From source file:org.springframework.batch.core.jsr.job.DefaultStepHandler.java

/**
 * Given a step and configuration, return true if the step should start,
 * false if it should not, and throw an exception if the job should finish.
 * @param lastStepExecution the last step execution
 * @param jobInstance//from w  w w  .  j a va2s. c om
 * @param step
 *
 * @throws StartLimitExceededException if the start limit has been exceeded
 * for this step
 * @throws JobRestartException if the job is in an inconsistent state from
 * an earlier failure
 */
@Override
protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step)
        throws JobRestartException, StartLimitExceededException {
    BatchStatus stepStatus;
    String restartStep = null;
    if (lastStepExecution == null) {
        jobExecution.getExecutionContext().put("batch.startedStep", step.getName());
        stepStatus = BatchStatus.STARTING;
    } else {
        stepStatus = lastStepExecution.getStatus();

        JobExecution lastJobExecution = getLastJobExecution(jobExecution);

        if (lastJobExecution.getExecutionContext().containsKey("batch.restartStep")) {
            restartStep = lastJobExecution.getExecutionContext().getString("batch.restartStep");

            if (CollectionUtils.isEmpty(jobExecution.getStepExecutions())
                    && lastJobExecution.getStatus() == BatchStatus.STOPPED
                    && StringUtils.hasText(restartStep)) {
                if (!restartStep.equals(step.getName())
                        && !jobExecution.getExecutionContext().containsKey("batch.startedStep")) {
                    logger.info("Job was stopped and should restart at step " + restartStep
                            + ".  The current step is " + step.getName());
                    return false;
                } else {
                    // Indicates the starting point for execution evaluation per JSR-352
                    jobExecution.getExecutionContext().put("batch.startedStep", step.getName());
                }
            }
        }
    }

    if (stepStatus == BatchStatus.UNKNOWN) {
        throw new JobRestartException("Cannot restart step 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.");
    }

    if ((stepStatus == BatchStatus.COMPLETED && step.isAllowStartIfComplete() == false)
            || stepStatus == BatchStatus.ABANDONED) {
        // step is complete, false should be returned, indicating that the
        // step should not be started
        logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution);
        return false;
    }

    if (getJobRepository().getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step
            .getStartLimit()) {
        // step start count is less than start max, return true
        return true;
    } else {
        // start max has been exceeded, throw an exception.
        throw new StartLimitExceededException("Maximum start limit exceeded for step: " + step.getName()
                + "StartMax: " + step.getStartLimit());
    }
}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testSimpleProperty() throws Exception {
    JobExecution jobExecution = new JobExecution(11L);
    ExecutionContext executionContext = jobExecution.getExecutionContext();
    executionContext.put("foo", "bar");
    JobSynchronizationManager.register(jobExecution);
    assertEquals("bar", simple.getName());
}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testGetMultipleInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        final Long id = 123L + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from   ww  w .  j  av a2s . c om*/
            public String call() throws Exception {
                JobExecution jobExecution = new JobExecution(id);
                ExecutionContext executionContext = jobExecution.getExecutionContext();
                executionContext.put("foo", value);
                JobContext context = JobSynchronizationManager.register(jobExecution);
                logger.debug("Registered: " + context.getJobExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    JobSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    int i = 0;
    for (FutureTask<String> task : tasks) {
        assertEquals("foo" + i, task.get());
        i++;
    }

}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testGetSameInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
    final JobExecution jobExecution = new JobExecution(11L);
    ExecutionContext executionContext = jobExecution.getExecutionContext();
    executionContext.put("foo", "foo");
    JobSynchronizationManager.register(jobExecution);
    assertEquals("foo", simple.getName());

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from   w  ww  . ja v a2 s .c om*/
            public String call() throws Exception {
                ExecutionContext executionContext = jobExecution.getExecutionContext();
                executionContext.put("foo", value);
                JobContext context = JobSynchronizationManager.register(jobExecution);
                logger.debug("Registered: " + context.getJobExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    JobSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    for (FutureTask<String> task : tasks) {
        assertEquals("foo", task.get());
    }

    // Don't close the outer scope until all tasks are finished. This should
    // always be the case if using an AbstractJob
    JobSynchronizationManager.close();

}