Example usage for org.springframework.batch.core JobParametersBuilder JobParametersBuilder

List of usage examples for org.springframework.batch.core JobParametersBuilder JobParametersBuilder

Introduction

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

Prototype

public JobParametersBuilder() 

Source Link

Document

Default constructor.

Usage

From source file:org.obiba.onyx.core.batch.OnyxJobDetailDelegate.java

private JobParameters getJobParametersFromJobMap(Map<String, Object> jobDataMap) {

    JobParametersBuilder builder = new JobParametersBuilder();

    for (Entry<String, Object> entry : jobDataMap.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof String && !key.equals(JOB_NAME)) {
            builder.addString(key, (String) value);
        } else if (value instanceof Float || value instanceof Double) {
            builder.addDouble(key, ((Number) value).doubleValue());
        } else if (value instanceof Integer || value instanceof Long) {
            builder.addLong(key, ((Number) value).longValue());
        } else if (value instanceof Date) {
            builder.addDate(key, (Date) value);
        } else {//  w ww .  j a  v a 2s.co m
            log.debug("JobDataMap contains values which are not job parameters (ignoring).");
        }
    }

    return builder.toJobParameters();

}

From source file:io.getlime.push.controller.rest.SendCampaignController.java

/**
 * Run sending job with campaignID and timestamp parameters.
 *
 * @param id Specific campaign ID.//w  ww.  j  a va 2 s. c o  m
 * @return Response with status.
 */
@RequestMapping(value = "live/{id}", method = RequestMethod.POST)
@ResponseBody
public Response sendCampaign(@PathVariable(value = "id") Long id) throws PushServerException {
    try {
        PushCampaignEntity campaign = pushCampaignRepository.findOne(id);
        if (campaign == null) {
            throw new PushServerException("Campaign with entered id does not exist");
        }
        JobParameters jobParameters = new JobParametersBuilder().addLong("campaignId", id)
                .addDate("timestamp", new Date()).toJobParameters();
        jobLauncher.run(job, jobParameters);
        return new Response();
    } catch (JobExecutionAlreadyRunningException e) {
        throw new PushServerException("Job execution already running");
    } catch (JobRestartException e) {
        throw new PushServerException("Job is restarted");
    } catch (JobInstanceAlreadyCompleteException e) {
        throw new PushServerException("Job instance already completed");
    } catch (JobParametersInvalidException e) {
        throw new PushServerException("Job parameters are invalid");
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.job.UserSyncJobIntegrationTests.java

@Test
public void testJobRunsWithNoFilters() throws Exception {
    Date dateInThePast = new Date(System.currentTimeMillis() - 10000);
    setUpModifiedUaaData(dateInThePast);
    JobExecution execution = jobLauncher.run(job, new JobParametersBuilder()
            .addDate("start.date", new Date(System.currentTimeMillis() - 100000)).toJobParameters());
    assertEquals(BatchStatus.COMPLETED, execution.getStatus());
    StepExecution stepExecution = execution.getStepExecutions().iterator().next();
    assertEquals(3, stepExecution.getReadCount());
    assertEquals(0, stepExecution.getFilterCount());
    // No records are updated, but the filter count is always write - read
    assertEquals(3, stepExecution.getWriteCount());
}

From source file:com.inkubator.hrm.web.payroll.PayTempOvertimeFormController.java

public void doSave() throws IOException {

    String pathUpload = facesIO.getPathUpload() + fileName;
    if (file != null) {
        facesIO.transferFile(file);/*from  w  w  w . j  a  v  a 2s.c o  m*/
        File fotoOldFile = new File(facesIO.getPathUpload() + fileName);
    }
    try {
        //running jobs batch to execute file upload
        JobParameters jobParameters = new JobParametersBuilder().addString("input.file.path", pathUpload)
                .addString("createdBy", UserInfoUtil.getUserName())
                .addString("timeInMilis", String.valueOf(System.currentTimeMillis())).toJobParameters();
        JobExecution jobExecution = jobLauncher.run(jobPayTempOvertimeUpload, jobParameters);

        //remove file upload
        //remove physical file
        try {
            File oldFile = new File(facesIO.getPathUpload() + fileName);
            oldFile.delete();
        } catch (Exception e) {
            //if any error when removing file, system will continue deleting the record
        }
        RequestContext.getCurrentInstance().closeDialog(HRMConstant.SAVE_CONDITION);
        cleanAndExit();
    } catch (Exception ex) {
        LOGGER.error("Error", ex);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.job.UserMigrationJobIntegrationTests.java

@Test
public void testJobRunsWithSkips() throws Exception {
    TestUtils.runScript(uaaDataSource, "add-name-constraints");
    TestUtils.deleteFrom(cloudControllerDataSource, "users");
    TestUtils.deleteFrom(uaaDataSource, "users");
    new JdbcTemplate(cloudControllerDataSource).update(
            "insert into users (id, active, email, crypted_password, created_at, updated_at) values (?, ?, ?, ?, ?, ?)",
            4, true, "invalid", "ENCRYPT_ME", new Date(), new Date());
    new JdbcTemplate(cloudControllerDataSource).update(
            "insert into users (id, active, email, crypted_password, created_at, updated_at) values (?, ?, ?, ?, ?, ?)",
            4, true, "vcap_tester@vmware.com", "ENCRYPT_ME", new Date(), new Date());
    JobExecution execution = jobLauncher.run(job,
            new JobParametersBuilder().addString("users", "marissa@test.org,vcap_tester@vmware.com")
                    .addLong("run.id", 1L).toJobParameters());
    assertEquals(BatchStatus.COMPLETED, execution.getStatus());
    Iterator<StepExecution> iterator = execution.getStepExecutions().iterator();
    assertEquals(1, iterator.next().getWriteSkipCount());
    assertEquals(1, iterator.next().getWriteCount());
    JdbcTemplate jdbcTemplate = new JdbcTemplate(uaaDataSource);
    assertEquals(1, jdbcTemplate.queryForInt("select count(*) from users"));
    assertEquals(1,// w  w  w  . j  a v a 2s.  c  om
            jdbcTemplate.queryForInt("select count(*) from users where authorities=?", "uaa.admin,uaa.user"));
}

From source file:com.ibm.zdu.ZduApplication.java

private static void executeBatchProcess(ZduConfig config) {
    // TODO read all CSV files that are placed in the path
    try {/*from  ww  w . j a v a2 s.  c o m*/
        // Execute the batch process
        Job createOrUpdateUserJob = ctx.getBean("createOrUpdateUserJob", Job.class);
        System.out.println("job.getName()***" + createOrUpdateUserJob.getName());
        JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
        JobStatusManager statusManager = BatchContextManager.getInstance()
                .initializeStatusManager(createOrUpdateUserJob.getName(), config);
        System.out.println("in application statusManager***" + statusManager);

        JobParameters jobParameters = new JobParametersBuilder().addDate("date", new Date()).toJobParameters();
        JobExecution jobExecution = jobLauncher.run(createOrUpdateUserJob, jobParameters);
    } catch (Exception e) {
    }
}

From source file:nu.yona.server.batch.service.BatchTaskService.java

public void sendSystemMessage(SystemMessageSendRequestDto request) {
    logger.info("Received request to send system message with text {}", request.getMessageText());

    JobParameters jobParameters = new JobParametersBuilder().addDate("uniqueInstanceId", new Date())
            .addString("messageText", request.getMessageText()).toJobParameters();
    launchImmediately(sendSystemMessageJob, jobParameters);
}

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

private ExitStatus executarJob(String nomeJob, String usuario, long anoMesRef, Date dtRef) {
    try {/* ww  w.ja v  a2 s .c  om*/

        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.wallride.service.PostService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }/*from  w  w w  . ja v  a  2s. c  o  m*/
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}