Example usage for org.springframework.batch.core.scope.context JobSynchronizationManager register

List of usage examples for org.springframework.batch.core.scope.context JobSynchronizationManager register

Introduction

In this page you can find the example usage for org.springframework.batch.core.scope.context JobSynchronizationManager register.

Prototype

public static JobContext register(JobExecution JobExecution) 

Source Link

Document

Register a context with the current thread - always put a matching #close() call in a finally block to ensure that the correct context is available in the enclosing block.

Usage

From source file:org.springframework.batch.core.job.AbstractJob.java

/**
 * Run the specified job, handling all listener and repository calls, and
 * delegating the actual processing to {@link #doExecute(JobExecution)}.
 *
 * @see Job#execute(JobExecution)//www .j  a  va2 s  . c  o  m
 * @throws StartLimitExceededException
 *             if start limit of one of the steps was exceeded
 */
@Override
public final void execute(JobExecution execution) {

    if (logger.isDebugEnabled()) {
        logger.debug("Job execution starting: " + execution);
    }

    JobSynchronizationManager.register(execution);

    try {

        jobParametersValidator.validate(execution.getJobParameters());

        if (execution.getStatus() != BatchStatus.STOPPING) {

            execution.setStartTime(new Date());
            updateStatus(execution, BatchStatus.STARTED);

            listener.beforeJob(execution);

            try {
                doExecute(execution);
                if (logger.isDebugEnabled()) {
                    logger.debug("Job execution complete: " + execution);
                }
            } catch (RepeatException e) {
                throw e.getCause();
            }
        } else {

            // The job was already stopped before we even got this far. Deal
            // with it in the same way as any other interruption.
            execution.setStatus(BatchStatus.STOPPED);
            execution.setExitStatus(ExitStatus.COMPLETED);
            if (logger.isDebugEnabled()) {
                logger.debug("Job execution was stopped: " + execution);
            }

        }

    } catch (JobInterruptedException e) {
        logger.info("Encountered interruption executing job: " + e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug("Full exception", e);
        }
        execution.setExitStatus(getDefaultExitStatusForFailure(e, execution));
        execution.setStatus(BatchStatus.max(BatchStatus.STOPPED, e.getStatus()));
        execution.addFailureException(e);
    } catch (Throwable t) {
        logger.error("Encountered fatal error executing job", t);
        execution.setExitStatus(getDefaultExitStatusForFailure(t, execution));
        execution.setStatus(BatchStatus.FAILED);
        execution.addFailureException(t);
    } finally {
        try {
            if (execution.getStatus().isLessThanOrEqualTo(BatchStatus.STOPPED)
                    && execution.getStepExecutions().isEmpty()) {
                ExitStatus exitStatus = execution.getExitStatus();
                ExitStatus newExitStatus = ExitStatus.NOOP
                        .addExitDescription("All steps already completed or no steps configured for this job.");
                execution.setExitStatus(exitStatus.and(newExitStatus));
            }

            execution.setEndTime(new Date());

            try {
                listener.afterJob(execution);
            } catch (Exception e) {
                logger.error("Exception encountered in afterStep callback", e);
            }

            jobRepository.update(execution);
        } finally {
            JobSynchronizationManager.release();
        }

    }

}

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/*www.j a va2  s.  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 w w.j a va  2  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();

}