org.springframework.batch.core.JobParametersBuilder Java Examples

The following examples show how to use org.springframework.batch.core.JobParametersBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JobServerServiceIT.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    try {
        final org.springframework.batch.core.JobExecution execution = this.jobLauncher.run(this.simpleJob, new JobParametersBuilder().addLong("time", System
                .currentTimeMillis())
                .toJobParameters());
        this.launchedJobExecutionId = execution.getId();
        this.launchedJobInstanceId = execution.getJobInstance().getId();
        final Collection<org.springframework.batch.core.StepExecution> stepExecutions = execution.getStepExecutions();
        for (final org.springframework.batch.core.StepExecution stepExecution : stepExecutions) {
            this.launchedStepExecutionId = stepExecution.getId();
        }
        this.jobExecution = execution;
    } catch (final Exception e) {
        fail(e.getMessage());
    }
}
 
Example #2
Source File: ServiceUtil.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
private static void attachJobParameter(final JobParametersBuilder jobParametersBuilder, final String parameterName,
                                       final Object parameterValue) {
    if (parameterValue instanceof Long) {
        jobParametersBuilder.addLong(parameterName, (Long) parameterValue);
    } else if (parameterValue instanceof Integer) {
        jobParametersBuilder.addLong(parameterName, Long.valueOf((Integer) parameterValue));
    } else if (parameterValue instanceof Date) {
        jobParametersBuilder.addDate(parameterName, (Date) parameterValue);
    } else if (parameterValue instanceof String) {
        jobParametersBuilder.addString(parameterName, (String) parameterValue);
    } else if (parameterValue instanceof Double) {
        jobParametersBuilder.addDouble(parameterName, (Double) parameterValue);
    } else {
        log.error("Could not add Parameter. Cause: Unsupported Parameter Type:" + parameterValue.getClass() + " !");
    }
}
 
Example #3
Source File: DefaultListenerServiceTest.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Test
public void testActivateListener() {
    final JobListenerConfiguration jobListenerConfiguration = DomainTestHelper.createJobListenerConfiguration
            ("src/test/", "*.txt", JobListenerType.LOCAL_FOLDER_LISTENER);
    jobListenerConfiguration.setBeanName("testBean");
    jobListenerConfiguration.setListenerStatus(ListenerStatus.ACTIVE);
    final JobConfiguration jobConfiguration = DomainTestHelper.createJobConfiguration(jobListenerConfiguration);
    final ListenerConstructorWrapper listenerConstructorWrapper = new ListenerConstructorWrapper();
    listenerConstructorWrapper.setJobIncrementer(JobIncrementer.DATE);
    listenerConstructorWrapper.setJob(this.job);
    listenerConstructorWrapper.setJobConfiguration(jobConfiguration);
    listenerConstructorWrapper.setJobLauncher(this.jobLauncher);
    listenerConstructorWrapper.setJobParameters(new JobParametersBuilder().toJobParameters());
    final FolderListener folderListener = new FolderListener(listenerConstructorWrapper);
    when(this.applicationContext.getBean(anyString(), any(Class.class))).thenReturn(folderListener);
    when(this.applicationContext.containsBean(anyString())).thenReturn(Boolean.TRUE);
    try {
        this.listenerService.activateListener("testBean", Boolean.FALSE);
    } catch (final Exception e) {
        fail(e.getMessage());
    }

}
 
Example #4
Source File: BeanRegistrarIT.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Test
public void registerPeriodSchedulerIT() {
    final JobSchedulerConfiguration jobSchedulerConfiguration = DomainTestHelper.createJobSchedulerConfiguration(null,
            10L, 10L, JobSchedulerType.PERIOD);
    final JobConfiguration jobConfiguration = DomainTestHelper.createJobConfiguration(jobSchedulerConfiguration);
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    final SchedulerConstructorWrapper schedulerConstructorWrapper = new SchedulerConstructorWrapper();
    schedulerConstructorWrapper.setJob(this.simpleJob);
    schedulerConstructorWrapper.setJobConfiguration(jobConfiguration);
    schedulerConstructorWrapper.setJobIncrementer(JobIncrementer.DATE);
    schedulerConstructorWrapper.setJobLauncher(this.jobLauncher);
    schedulerConstructorWrapper.setJobParameters(new JobParametersBuilder().toJobParameters());
    schedulerConstructorWrapper.setThreadPoolTaskScheduler(scheduler);
    final Set<Object> constructorValues = new HashSet<>();
    constructorValues.add(schedulerConstructorWrapper);
    this.beanRegistrar
            .registerBean(PeriodScheduler.class, "sampleBeanRegistrar", constructorValues, null, null, null, null);
    final PeriodScheduler periodScheduler = this.applicationContext.getBean("sampleBeanRegistrar", PeriodScheduler
            .class);
    assertThat(periodScheduler).isNotNull();
    periodScheduler.schedule();
    this.applicationContext.close();
}
 
Example #5
Source File: DefaultListenerServiceTest.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminateListener() {
    final JobListenerConfiguration jobListenerConfiguration = DomainTestHelper.createJobListenerConfiguration
            ("src/test/", "*.txt", JobListenerType.LOCAL_FOLDER_LISTENER);
    jobListenerConfiguration.setBeanName("testBean");
    jobListenerConfiguration.setListenerStatus(ListenerStatus.ACTIVE);
    final JobConfiguration jobConfiguration = DomainTestHelper.createJobConfiguration(jobListenerConfiguration);
    final ListenerConstructorWrapper listenerConstructorWrapper = new ListenerConstructorWrapper();
    listenerConstructorWrapper.setJobIncrementer(JobIncrementer.DATE);
    listenerConstructorWrapper.setJob(this.job);
    listenerConstructorWrapper.setJobConfiguration(jobConfiguration);
    listenerConstructorWrapper.setJobLauncher(this.jobLauncher);
    listenerConstructorWrapper.setJobParameters(new JobParametersBuilder().toJobParameters());
    final FolderListener folderListener = new FolderListener(listenerConstructorWrapper);
    when(this.applicationContext.getBean(anyString(), any(Class.class))).thenReturn(folderListener);
    when(this.applicationContext.containsBean(anyString())).thenReturn(Boolean.TRUE);
    try {
        this.listenerService.terminateListener("testBean");
    } catch (final Exception e) {
        fail(e.getMessage());
    }

}
 
Example #6
Source File: PostService.java    From wallride with Apache License 2.0 6 votes vote down vote up
@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;
		}
	}

	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);
	}
}
 
Example #7
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@DirtiesContext
@Test
public void retryFailedExecutionOnNonRestartableJob() throws Exception {
	this.job = this.jobs.get("job").preventRestart()
			.start(this.steps.get("step").tasklet(throwingTasklet()).build())
			.incrementer(new RunIdIncrementer()).build();
	runFailedJob(new JobParameters());
	runFailedJob(new JobParameters());
	// A failed job that is not restartable does not re-use the job params of
	// the last execution, but creates a new job instance when running it again.
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2);

	// try to re-run a failed execution
	Executable executable = () -> this.runner.execute(this.job,
			new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
	assertThatExceptionOfType(JobRestartException.class)
			.isThrownBy(executable::execute)
			.withMessage("JobInstance already exists and is not restartable");
}
 
Example #8
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@DirtiesContext
@Test
public void runDifferentInstances() throws Exception {
	this.job = this.jobs.get("job")
			.start(this.steps.get("step").tasklet(throwingTasklet()).build()).build();
	// start a job instance
	JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo")
			.toJobParameters();
	runFailedJob(jobParameters);
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
	// start a different job instance
	JobParameters otherJobParameters = new JobParametersBuilder()
			.addString("name", "bar").toJobParameters();
	runFailedJob(otherJobParameters);
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2);
}
 
Example #9
Source File: BatchConfiguration.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
CommandLineRunner runner(JobLauncher launcher,
                         Job job,
                         @Value("${file}") File in,
                         JdbcTemplate jdbcTemplate) {
    return args -> {

        JobExecution execution = launcher.run(job,
                new JobParametersBuilder()
                        .addString("file", in.getAbsolutePath())
                        .toJobParameters());

        System.out.println("execution status: " + execution.getExitStatus().toString());

        List<Person> personList = jdbcTemplate.query("select * from PEOPLE", (resultSet, i) -> new Person(resultSet.getString("first"),
                resultSet.getString("last"),
                resultSet.getString("email")));

        personList.forEach(System.out::println);

    };

}
 
Example #10
Source File: IntegrationConfiguration.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
@Bean
IntegrationFlow batchJobFlow(Job job,
                             JdbcTemplate jdbcTemplate,
                             JobLauncher launcher,
                             MessageChannel files) {

    return IntegrationFlows.from(files)
            .transform((GenericTransformer<Object,JobLaunchRequest>) file -> {
                System.out.println(file.toString());
                System.out.println(file.getClass());
                return null ;
            })
            .transform((GenericTransformer<File, JobLaunchRequest>) file -> {
                JobParameters jp = new JobParametersBuilder()
                        .addString("file", file.getAbsolutePath())
                        .toJobParameters();
                return new JobLaunchRequest(job, jp);
            })
            .handle(new JobLaunchingGateway(launcher))
            .handle(JobExecution.class, (payload, headers) -> {
                System.out.println("job execution status: " + payload.getExitStatus().toString());

                List<Person> personList = jdbcTemplate.query("select * from PEOPLE",
                        (resultSet, i) -> new Person(resultSet.getString("first"),
                                resultSet.getString("last"),
                                resultSet.getString("email")));

                personList.forEach(System.out::println);
                return null;
            })
            .get();

}
 
Example #11
Source File: TaxCalculationStepITest.java    From batchers with Apache License 2.0 6 votes vote down vote up
@Test
public void taxCalculationStep_generatesCorrectCalculation() throws Exception {
    Employee employee = haveOneEmployee();

    JobParameters jobParameters = new JobParametersBuilder()
            .addLong("year", 2014L, true)
            .addLong("month", 5L, true)
            .toJobParameters();

    JobExecution jobExecution = jobLauncherTestUtils.launchStep(EmployeeJobConfigSingleJvm.TAX_CALCULATION_STEP, jobParameters);

    assertThat(jobExecution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);

    List<TaxCalculation> byEmployee = taxCalculationRepository.findByEmployee(employee);

    assertThat(byEmployee).hasSize(1);
    TaxCalculation taxCalculation = byEmployee.get(0);
    assertThat(taxCalculation.getEmployee().getId()).isEqualTo(employee.getId());
    assertThat(taxCalculation.getYear()).isEqualTo(2014);
    assertThat(taxCalculation.getMonth()).isEqualTo(5);

    List<TaxCalculation> byYearAndMonth = taxCalculationRepository.find(2014, 5, 1L);
    assertThat(byYearAndMonth).hasSize(1);
}
 
Example #12
Source File: SettleQuartzController.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * @param jobNameStr   任务名字符串
 * @param jobNameDesc  任务名描述
 * @param time         随机数:批量的唯一标志(非断点续跑可直接传null)
 * @param parameterMap 其它参数:不会作为批量的唯一标志(无参可传null)
 * Comment by 玄玉<https://jadyer.cn/> on 2019/8/12 18:25.
 */
private JobExecution runJob(String jobNameStr, String jobNameDesc, String time, Map<String, String> parameterMap) throws Exception {
    //判断是否断点续跑
    boolean isResume = false;
    long timeLong;
    if(StringUtils.isBlank(time)){
        timeLong = SystemClockUtil.INSTANCE.now();
    }else{
        isResume = true;
        timeLong = Long.parseLong(time);
    }
    LogUtil.getLogger().info("{}==>{}:Starting...time={}", jobNameDesc, isResume?":断点续跑":"", timeLong);
    //构造JobParameters
    JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
    jobParametersBuilder.addLong("time", timeLong);
    if(null!=parameterMap && !parameterMap.isEmpty()){
        for(Map.Entry<String,String> entry : parameterMap.entrySet()){
            jobParametersBuilder.addString(entry.getKey(), entry.getValue(), false);
        }
    }
    //执行job
    Job xmlSettleJob = (Job)SpringContextHolder.getBean(jobNameStr);
    JobExecution execution = jobLauncher.run(xmlSettleJob, jobParametersBuilder.toJobParameters());
    LogUtil.getLogger().info("{}==>{}:Ending......jobInstance={}", jobNameDesc, isResume?":断点续跑":"", execution.getJobInstance());
    return execution;
}
 
Example #13
Source File: SettleQuartzController.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * SpringBatch的断点续跑
 * -----------------------------------------------------------------------------------------------
 * 执行Step过程中发生异常时,而该异常又没有被配置为skip,那么整个Job会中断
 * 当人工修正完异常数据后,再次调用jobLauncher.run(),SpringBatch会从上次异常的地方开始跑
 * 1、当Step为读处理写时,假设10条数据,Step配置chunk=3(表明每三条Write一次),若第5条出现异常
 *    那么前三条可以成功Write,第4条即便处理成功也不会写入数据库,在修复后再跑的时,会从第4条开始读
 * 2、当Step为Tasklet时,仅当Tasklet全部执行完,且未发生异常,才会真正的提交事务,写入数据到数据库
 *    即只要其中某一条数据处理时发生异常,那么无论之前提交了多少次数据到数据库,都不会真正的写入数据库
 * 3、当并行Step中的某个Step出现异常时,那么并行中的其它Step不受影响,会继续跑完,然后才会中断Job
 *    修复数据后再跑时,会直接从并行中发生异常的该Step开始跑,其它未发生异常的并行中的Step不会重复跑
 * 注意:断点续跑时,传入的jobParameters必须相同,否则会认为是另一个任务,会从头跑,不会从断点的地方跑
 *      也就是说,这一切都建立在jobParameters传值相同的条件下
 * 另外:对于JobOperator.start()和restart()两个方法都试过,都没实现断点续跑的功能
 * -----------------------------------------------------------------------------------------------
 */
@RequestMapping("/batch")
//@SeedQSSReg(qssHost="${qss.host}", appHost="${qss.appHost}", appname="${qss.appname}", name="${qss.name}", cron="${qss.cron}")
CommResult<JobInstance> batch(String bizDate) throws Exception {
    //判断是否断点续跑
    boolean isResume = false;
    if(StringUtils.isBlank(bizDate)){
        bizDate = DateFormatUtils.format(new Date(), "yyyyMMdd");
    }else{
        isResume = true;
    }
    LogUtil.getLogger().info("结算跑批{}:Starting...bizDate={}", isResume?":断点续跑":"", bizDate);
    //构造JobParameters
    JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
    jobParametersBuilder.addString("bizDate", bizDate);
    //执行job
    JobExecution execution = jobLauncher.run(settleJob, jobParametersBuilder.toJobParameters());
    LogUtil.getLogger().info("结算跑批{}:Ending......", isResume?":断点续跑":"");
    return CommResult.success(execution.getJobInstance());
}
 
Example #14
Source File: ProtocolListenerTest.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Test
public void createProtocol() throws Exception {
	// Given
	JobExecution jobExecution = new JobExecution(1L,
			new JobParametersBuilder().addString("test", "value").toJobParameters());
	jobExecution.setJobInstance(new JobInstance(1L, "test-job"));
	jobExecution.setCreateTime(new Date());
	jobExecution.setStartTime(new Date());
	jobExecution.setEndTime(new Date());
	jobExecution.setExitStatus(new ExitStatus("COMPLETED_WITH_ERRORS", "This is a default exit message"));
	jobExecution.getExecutionContext().put("jobCounter", 1);
	StepExecution stepExecution = jobExecution.createStepExecution("test-step-1");
	stepExecution.getExecutionContext().put("stepCounter", 1);
	ProtocolListener protocolListener = new ProtocolListener();
	// When
	protocolListener.afterJob(jobExecution);
	// Then
	String output = this.outputCapture.toString();
	assertThat(output, containsString("Protocol for test-job"));
	assertThat(output, containsString("COMPLETED_WITH_ERRORS"));
}
 
Example #15
Source File: MapLightminJobExecutionDaoTest.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    final MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean();
    mapJobRepositoryFactoryBean.getObject();
    this.jobExecutionDao = mapJobRepositoryFactoryBean.getJobExecutionDao();
    this.jobInstanceDao = mapJobRepositoryFactoryBean.getJobInstanceDao();
    final MapJobExplorerFactoryBean mapJobExplorerFactoryBean = new MapJobExplorerFactoryBean(
            mapJobRepositoryFactoryBean);
    this.jobExplorer = mapJobExplorerFactoryBean.getObject();
    this.mapLightminJobExecutionDao = new MapLightminJobExecutionDao(this.jobExplorer);
    this.jobInstance = this.jobInstanceDao.createJobInstance("someJob", new JobParametersBuilder().toJobParameters());
    final List<JobExecution> jobExecutions = DomainTestHelper.createJobExecutions(JOB_EXECUTION_COUNT);
    for (final JobExecution jobExecution : jobExecutions) {
        jobExecution.setId(null);
        jobExecution.setJobInstance(this.jobInstance);
        this.jobExecutionDao.saveJobExecution(jobExecution);
    }
}
 
Example #16
Source File: JobServerServiceIT.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    try {
        final org.springframework.batch.core.JobExecution execution = this.jobLauncher.run(this.simpleJob, new JobParametersBuilder().addLong("time", System
                .currentTimeMillis())
                .toJobParameters());
        this.launchedJobExecutionId = execution.getId();
        this.launchedJobInstanceId = execution.getJobInstance().getId();
        final Collection<org.springframework.batch.core.StepExecution> stepExecutions = execution.getStepExecutions();
        for (final org.springframework.batch.core.StepExecution stepExecution : stepExecutions) {
            this.launchedStepExecutionId = stepExecution.getId();
        }
        this.jobExecution = execution;
    } catch (final Exception e) {
        fail(e.getMessage());
    }
}
 
Example #17
Source File: BatchServiceTest.java    From SpringBootBucket with MIT License 6 votes vote down vote up
/**
    CREATE TABLE Z_TEST_APP (
        appid INT,
        zname VARCHAR2 (20),
        flag VARCHAR2 (2),
        CONSTRAINT app_pk PRIMARY KEY (appid)
     );

     CREATE TABLE Z_TEST_LOG (
        logid INT,
        msg VARCHAR2 (20),
        logtime VARCHAR2 (8),
        CONSTRAINT log_pk PRIMARY KEY (logid)
     );
 * @throws Exception
 */
@Test
public void testTwoJobs() throws Exception {
    JobParameters jobParameters1 = new JobParametersBuilder()
            .addLong("time", System.currentTimeMillis())
            .addString("input.file.name", p.getCsvApp())
            .toJobParameters();
    jobLauncher.run(zappJob, jobParameters1);

    JobParameters jobParameters2 = new JobParametersBuilder()
            .addLong("time", System.currentTimeMillis())
            .addString("input.file.name", p.getCsvLog())
            .toJobParameters();
    jobLauncher.run(zlogJob, jobParameters2);

    logger.info("Main线程执行完成");
    while (true) {
        Thread.sleep(2000000L);
    }
}
 
Example #18
Source File: App.java    From tutorials with MIT License 6 votes vote down vote up
private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) {
    final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    final Job job = (Job) context.getBean(batchJobName);

    LOGGER.info("Starting the batch job: {}", batchJobName);
    try {
        // To enable multiple execution of a job with the same parameters
        JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis()))
            .toJobParameters();
        final JobExecution execution = jobLauncher.run(job, jobParameters);
        LOGGER.info("Job Status : {}", execution.getStatus());
    } catch (final Exception e) {
        e.printStackTrace();
        LOGGER.error("Job failed {}", e.getMessage());
    }
}
 
Example #19
Source File: JobLaunchService.java    From spring-cloud with Apache License 2.0 6 votes vote down vote up
public JobResult launchJob(Job job) {
    try {
        JobParameters jobParameters = new JobParametersBuilder()
                .addDate("timestamp", Calendar.getInstance().getTime())
                .toJobParameters();
        JobExecution jobExecution = jobLauncher.run(job, jobParameters);
        return JobResult.builder()
                .jobName(job.getName())
                .jobId(jobExecution.getJobId())
                .jobExitStatus(jobExecution.getExitStatus())
                .timestamp(Calendar.getInstance().getTimeInMillis())
                .build();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new RuntimeException("launch job exception ", e);
    }
}
 
Example #20
Source File: HelloWorldBatchTest.java    From blog with MIT License 5 votes vote down vote up
@Test
public void test_That_batch_execution_Should_stop_When_wrong_format_arg()
        throws Exception {
    JobExecution jobExecution = jobLauncherTestUtils
            .launchJob(new JobParametersBuilder().addLong(
                    "execution.times", null).toJobParameters());
    assertEquals(BatchStatus.FAILED, jobExecution.getStatus());
}
 
Example #21
Source File: HelloWorldBatchTest.java    From blog with MIT License 5 votes vote down vote up
@Test
public void test_That_batch_execution_Should_success_When_launch_with_valid_args()
        throws Exception {
    // arrange
    JobParameters params = new JobParametersBuilder().addLong(
            "execution.times", 10L).toJobParameters();
    // act
    JobExecution jobExecution = jobLauncherTestUtils.launchJob(params);
    // assert
    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
    assertEquals(1, jobExecution.getStepExecutions().size());
    StepExecution step = jobExecution.getStepExecutions().iterator().next();
    assertEquals(11, step.getCommitCount());
    assertEquals(10, step.getWriteCount());
}
 
Example #22
Source File: JobLauncherDetails.java    From spring-batch-quartz-admin with Apache License 2.0 5 votes vote down vote up
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(Constants.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 {
                // JobDataMap contains values which are not job parameters
                // (ignoring)
            }
        }

        // Needs a unique job parameter to rerun the completed job
        builder.addDate(Constants.JOB_RUN_DATE, new Date());

        return builder.toJobParameters();

    }
 
Example #23
Source File: SpringBatchApplication.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void run(String... args) throws Exception {
    JobParametersBuilder paramsBuilder = new JobParametersBuilder();
    paramsBuilder.addString("file.input", input);
    paramsBuilder.addString("file.output", output);
    jobLauncher.run(transformBooksRecordsJob, paramsBuilder.toJobParameters());
}
 
Example #24
Source File: SpringBatchScheduler.java    From tutorials with MIT License 5 votes vote down vote up
@Scheduled(fixedRate = 2000)
public void launchJob() throws Exception {
    Date date = new Date();
    logger.debug("scheduler starts at " + date);
    if (enabled.get()) {
        JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", date)
            .toJobParameters());
        batchRunCounter.incrementAndGet();
        logger.debug("Batch job ends with status as " + jobExecution.getStatus());
    }
    logger.debug("scheduler ends ");
}
 
Example #25
Source File: JdbcBatchTest.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void jobTest() {

	JobParametersBuilder builder = new JobParametersBuilder();
	try {
		JobExecution execution = jobLauncher.run(validJob, builder.toJobParameters());
		assertEquals(BatchStatus.COMPLETED, execution.getStatus());
	} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
			| JobParametersInvalidException e) {
		e.printStackTrace();
	}

}
 
Example #26
Source File: ThreadedPerformanceTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockServer = MockRestServiceServer.createServer(restTemplate);
    SmtpServerStub.start();
    jobParams = new JobParametersBuilder()
            .addLong("month", 2L)
            .addLong("year", 2014L).toJobParameters();

    employeeGeneratorService.resetEmployees(NUMBER_OF_EMPLOYEES);
    runningTimeService.setMaximumTime(51);
    runningTimeService.setMinimumTime(50);

    jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
}
 
Example #27
Source File: JobInvokerController.java    From POC with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/run-batch-job")
public String handle() throws Exception {

	JobParameters jobParameters = new JobParametersBuilder().addString("key", "Post")
			.addDate("currentDate", new Date()).toJobParameters();
	this.jobLauncher.run(this.executionJob, jobParameters);

	return "Batch job has been invoked";
}
 
Example #28
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@DirtiesContext
@Test
public void basicExecution() throws Exception {
	this.runner.execute(this.job, new JobParameters());
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
	this.runner.execute(this.job,
			new JobParametersBuilder().addLong("id", 1L).toJobParameters());
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2);
}
 
Example #29
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@DirtiesContext
@Test
public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception {
	this.job = this.jobs.get("job")
			.start(this.steps.get("step").tasklet(throwingTasklet()).build())
			.incrementer(new RunIdIncrementer()).build();
	JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false)
			.addLong("foo", 2L, false).toJobParameters();
	runFailedJob(jobParameters);
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
	runFailedJob(new JobParametersBuilder(jobParameters).addLong("run.id", 1L)
			.toJobParameters());
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
}
 
Example #30
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@DirtiesContext
@Test
public void retryFailedExecution() throws Exception {
	this.job = this.jobs.get("job")
			.start(this.steps.get("step").tasklet(throwingTasklet()).build())
			.incrementer(new RunIdIncrementer()).build();
	runFailedJob(new JobParameters());
	runFailedJob(new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
	assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
}