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

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

Introduction

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

Prototype

public void setExecutionContext(ExecutionContext executionContext) 

Source Link

Document

Sets the ExecutionContext for this execution

Usage

From source file:br.com.postalis.folhapgto.service.SvcFolhaPgtoImpl.java

private ExitStatus executarJob(String nomeJob, String usuario, long anoMesRef, Date dtRef) {
    try {//from   ww w  .  j  av  a2  s . c o m

        appContext = new ClassPathXmlApplicationContext("spring/batch/jobs/jobMov.xml");

        JobLauncher jobLauncher = (JobLauncher) appContext.getBean("jobLauncher");
        Job job = (Job) appContext.getBean(nomeJob);

        LOGGER.info("Iniciando o Processo " + nomeJob + "...");

        JobParameters jobParams = new JobParametersBuilder()

                .addDate("dtReferencia", dtRef).addLong("anoMesRef", anoMesRef).addString("usuario", usuario)
                .toJobParameters();

        execution = jobLauncher.run(job, jobParams);
        LOGGER.info("Hora inicial: " + execution.getStartTime());
        LOGGER.info("Status do processamento : " + execution.getStatus());
        LOGGER.info("Hora Final: " + execution.getEndTime());
        LOGGER.info("Fim do Processo!!!");
        LOGGER.info(execution.toString());

        String nomeLog = "";
        SimpleDateFormat formatComHora = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat formatSemHora = new SimpleDateFormat("dd-MM-yyyy");
        if (nomeJob.equalsIgnoreCase("ImportarRubricasFolhaPgto")) {
            nomeLog = (String) execution.getExecutionContext().get("nomeLog");
        } else if (nomeJob.equalsIgnoreCase("consultarDescPosFolha")) {
            nomeLog = "ImportarDescPosFolhaECT_" + formatSemHora.format(dtRef) + "_"
                    + formatComHora.format(DateTime.now().toDate());
        } else if (nomeJob.equalsIgnoreCase("consultarLogImportacao")) {
            nomeLog = "ImportarLogImportacaoECT_" + formatSemHora.format(dtRef) + "_"
                    + formatComHora.format(DateTime.now().toDate());
        } else if (nomeJob.equalsIgnoreCase("consultarRubIncorporadas")) {
            nomeLog = "ImportarRubricasIncorporadasECT_" + formatSemHora.format(dtRef) + "_"
                    + formatComHora.format(DateTime.now().toDate());
        } else {
            nomeLog = "LogGeral_" + formatSemHora.format(dtRef) + "_"
                    + formatComHora.format(DateTime.now().toDate());
        }
        renomearArquivoDeLog(nomeLog);

        resultado = new ExitStatus(execution.getExitStatus().getExitCode());

    } catch (Exception e) {
        LOGGER.error("Erro ProcBatchJobMov: " + e.getMessage());
    } finally {
        //execution.setExecutionContext(null);
        for (StepExecution stepExecution : execution.getStepExecutions()) {
            stepExecution.setExecutionContext(null);
            //  jobRepository.updateExecutionContext(stepExecution);
        }
        //jobRepository.updateExecutionContext(execution);
    }

    return resultado;
}

From source file:org.obiba.onyx.core.etl.participant.impl.AppointmentListUpdateListenerTest.java

@Test
public void testAfterUpdateCompleted() {
    Map<String, JobParameter> jobParameterMap = new HashMap<String, JobParameter>();
    jobParameterMap.put("date", new JobParameter(new Date()));
    JobInstance job = new JobInstance(1l, new JobParameters(jobParameterMap), "jobTest");
    StepExecution stepExecution = new StepExecution("compltion", new JobExecution(job));
    stepExecution.setExitStatus(ExitStatus.COMPLETED);
    ExecutionContext context = new ExecutionContext();
    context.put("fileName", "fileName.xls");
    stepExecution.setExecutionContext(context);

    appointmentManagementServiceMock.saveAppointmentUpdateStats((AppointmentUpdateStats) EasyMock.anyObject());

    replay(appointmentManagementServiceMock);
    appointmentListUpdateListener.afterUpdateCompleted(stepExecution);
    verify(appointmentManagementServiceMock);

}

From source file:com.xchanging.support.batch.admin.service.SimpleJobService.java

public StepExecution getStepExecution(Long jobExecutionId, Long stepExecutionId)
        throws NoSuchJobExecutionException, NoSuchStepExecutionException {
    JobExecution jobExecution = getJobExecution(jobExecutionId);
    StepExecution stepExecution = stepExecutionDao.getStepExecution(jobExecution, stepExecutionId);
    if (stepExecution == null) {
        throw new NoSuchStepExecutionException("There is no StepExecution with jobExecutionId=" + jobExecutionId
                + " and id=" + stepExecutionId);
    }/*w w  w .j a v a  2  s. c  o m*/
    try {
        stepExecution.setExecutionContext(executionContextDao.getExecutionContext(stepExecution));
    } catch (Exception e) {
        logger.info("Cannot load execution context for step execution: " + stepExecution);
    }
    return stepExecution;
}

From source file:admin.service.SimpleJobService.java

@Override
public StepExecution getStepExecution(Long jobExecutionId, Long stepExecutionId)
        throws NoSuchJobExecutionException, NoSuchStepExecutionException {
    JobExecution jobExecution = getJobExecution(jobExecutionId);
    StepExecution stepExecution = stepExecutionDao.getStepExecution(jobExecution, stepExecutionId);
    if (stepExecution == null) {
        throw new NoSuchStepExecutionException("There is no StepExecution with jobExecutionId=" + jobExecutionId
                + " and id=" + stepExecutionId);
    }//from w  w w  .  ja va 2  s.  co  m
    try {
        stepExecution.setExecutionContext(executionContextDao.getExecutionContext(stepExecution));
    } catch (Exception e) {
        logger.info("Cannot load execution context for step execution: " + stepExecution);
    }
    return stepExecution;
}

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

@Override
public StepExecution handleStep(Step step, JobExecution execution)
        throws JobInterruptedException, JobRestartException, StartLimitExceededException {
    if (execution.isStopping()) {
        throw new JobInterruptedException("JobExecution interrupted.");
    }//from w  w  w. ja v a 2  s .  com

    JobInstance jobInstance = execution.getJobInstance();

    StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobInstance, step.getName());
    if (stepExecutionPartOfExistingJobExecution(execution, lastStepExecution)) {
        // If the last execution of this step was in the same job, it's
        // probably intentional so we want to run it again...
        logger.info(String.format(
                "Duplicate step [%s] detected in execution of job=[%s]. "
                        + "If either step fails, both will be executed again on restart.",
                step.getName(), jobInstance.getJobName()));
        lastStepExecution = null;
    }
    StepExecution currentStepExecution = lastStepExecution;

    if (shouldStart(lastStepExecution, execution, step)) {

        currentStepExecution = execution.createStepExecution(step.getName());

        boolean isRestart = (lastStepExecution != null
                && !lastStepExecution.getStatus().equals(BatchStatus.COMPLETED));

        if (isRestart) {
            currentStepExecution.setExecutionContext(lastStepExecution.getExecutionContext());

            if (lastStepExecution.getExecutionContext().containsKey("batch.executed")) {
                currentStepExecution.getExecutionContext().remove("batch.executed");
            }
        } else {
            currentStepExecution.setExecutionContext(new ExecutionContext(executionContext));
        }

        jobRepository.add(currentStepExecution);

        logger.info("Executing step: [" + step.getName() + "]");
        try {
            step.execute(currentStepExecution);
            currentStepExecution.getExecutionContext().put("batch.executed", true);
        } catch (JobInterruptedException e) {
            // Ensure that the job gets the message that it is stopping
            // and can pass it on to other steps that are executing
            // concurrently.
            execution.setStatus(BatchStatus.STOPPING);
            throw e;
        }

        jobRepository.updateExecutionContext(execution);

        if (currentStepExecution.getStatus() == BatchStatus.STOPPING
                || currentStepExecution.getStatus() == BatchStatus.STOPPED) {
            // Ensure that the job gets the message that it is stopping
            execution.setStatus(BatchStatus.STOPPING);
            throw new JobInterruptedException("Job interrupted by step execution");
        }

    }

    return currentStepExecution;
}

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);
            }//www  .j  av  a 2  s  . c om
        }
    }

    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.step.item.FaultTolerantStepFactoryBeanRetryTests.java

@Test
public void testRestartAfterFailedWrite() throws Exception {

    factory.setSkipLimit(0);//w ww.j a  va 2 s . com
    factory.setCommitInterval(3);
    AbstractItemCountingItemStreamItemReader<String> reader = new AbstractItemCountingItemStreamItemReader<String>() {

        private ItemReader<String> reader;

        @Override
        protected void doClose() throws Exception {
            reader = null;
        }

        @Override
        protected void doOpen() throws Exception {
            reader = new ListItemReader<String>(Arrays.asList("a", "b", "c", "d", "e", "f"));
        }

        @Override
        protected String doRead() throws Exception {
            return reader.read();
        }

    };
    // Need to set name or else reader will fail to open
    reader.setName("foo");
    factory.setItemReader(reader);
    factory.setStreams(new ItemStream[] { reader });
    factory.setItemWriter(new ItemWriter<String>() {
        @Override
        public void write(List<? extends String> items) throws Exception {
            if (fail && items.contains("e")) {
                throw new RuntimeException("Planned failure");
            }
            processed.addAll(items);
        }
    });
    factory.setRetryLimit(0);
    Step step = factory.getObject();

    fail = true;
    StepExecution stepExecution = new StepExecution(step.getName(), jobExecution);
    repository.add(stepExecution);
    step.execute(stepExecution);

    assertEquals(BatchStatus.FAILED, stepExecution.getStatus());
    assertEquals(4, stepExecution.getWriteCount());
    assertEquals(6, stepExecution.getReadCount());

    fail = false;
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    stepExecution = new StepExecution(step.getName(), jobExecution);
    stepExecution.setExecutionContext(executionContext);
    repository.add(stepExecution);
    step.execute(stepExecution);

    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
    assertEquals(2, stepExecution.getWriteCount());
    assertEquals(2, stepExecution.getReadCount());
}