Java Code Examples for org.springframework.batch.core.launch.JobLauncher

The following examples show how to use org.springframework.batch.core.launch.JobLauncher. These examples are extracted from open source projects. 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 Project: spring-batch-rest   Source File: QuartzJobLauncher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext context) {
	String jobName = null;
	try {

		JobDetail jobDetail = context.getJobDetail();
		JobParameters jobParams = new JobParameters();
		if (jobDetail instanceof JobParamsDetail) {
			jobParams = JobParamUtil.convertRawToJobParams(((JobParamsDetail) jobDetail).getRawJobParameters());
		}

		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		jobName = dataMap.getString(JOB_NAME);

		JobLocator jobLocator = (JobLocator) context.getScheduler().getContext().get(JOB_LOCATOR);
		JobLauncher jobLauncher = (JobLauncher) context.getScheduler().getContext().get(JOB_LAUNCHER);

		Job job = jobLocator.getJob(jobName);
		log.info("Starting {}", job.getName());
		JobExecution jobExecution = jobLauncher.run(job, jobParams);
		log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
	} catch (Exception e) {
		log.error("Job {} failed", jobName, e);
	}
}
 
Example 2
@Bean
SpringBatchFlowRunner mySpringBatchFlowRunner(
		StepBuilderFactory stepBuilderFactory,
		JobBuilderFactory jobBuilderFactory,
		ProjectsToRunFactory projectsToRunFactory, JobLauncher jobLauncher,
		FlowRunnerTaskExecutorSupplier flowRunnerTaskExecutorSupplier,
		ConfigurableApplicationContext context,
		ReleaserProperties releaserProperties, BuildReportHandler reportHandler) {
	return new SpringBatchFlowRunner(stepBuilderFactory, jobBuilderFactory,
			projectsToRunFactory, jobLauncher, flowRunnerTaskExecutorSupplier,
			context, releaserProperties, reportHandler) {
		@Override
		Decision decide(Options options, ReleaserTask task) {
			return Decision.CONTINUE;
		}
	};
}
 
Example 3
SpringBatchFlowRunner(StepBuilderFactory stepBuilderFactory,
		JobBuilderFactory jobBuilderFactory,
		ProjectsToRunFactory projectsToRunFactory, JobLauncher jobLauncher,
		FlowRunnerTaskExecutorSupplier flowRunnerTaskExecutorSupplier,
		ConfigurableApplicationContext context, ReleaserProperties releaserProperties,
		BuildReportHandler reportHandler) {
	this.stepBuilderFactory = stepBuilderFactory;
	this.jobBuilderFactory = jobBuilderFactory;
	this.projectsToRunFactory = projectsToRunFactory;
	this.jobLauncher = jobLauncher;
	this.flowRunnerTaskExecutorSupplier = flowRunnerTaskExecutorSupplier;
	this.stepSkipper = new ConsoleInputStepSkipper(context, reportHandler);
	this.releaserProperties = releaserProperties;
	this.executorService = Executors.newFixedThreadPool(
			this.releaserProperties.getMetaRelease().getReleaseGroupThreadCount());
}
 
Example 4
Source Project: building-microservices   Source File: BatchConfiguration.java    License: 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 5
public TaskJobLauncherCommandLineRunnerFactoryBean(JobLauncher jobLauncher,
		JobExplorer jobExplorer, List<Job> jobs,
		TaskBatchProperties taskBatchProperties, JobRegistry jobRegistry,
		JobRepository jobRepository, BatchProperties batchProperties) {
	Assert.notNull(taskBatchProperties, "taskBatchProperties must not be null");
	Assert.notNull(batchProperties, "batchProperties must not be null");
	this.jobLauncher = jobLauncher;
	this.jobExplorer = jobExplorer;
	Assert.notEmpty(jobs, "jobs must not be null nor empty");
	this.jobs = jobs;
	this.jobNames = taskBatchProperties.getJobNames();
	this.jobRegistry = jobRegistry;
	this.taskBatchProperties = taskBatchProperties;
	if (StringUtils.hasText(batchProperties.getJob().getNames())) {
		this.jobNames = batchProperties.getJob().getNames();
	}
	else {
		this.jobNames = taskBatchProperties.getJobNames();
	}
	this.order = taskBatchProperties.getCommandLineRunnerOrder();
	this.jobRepository = jobRepository;
}
 
Example 6
Source Project: tutorials   Source File: SpringbatchPartitionerApp.java    License: MIT License 6 votes vote down vote up
public static void main(final String[] args) {
    // Spring Java config
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(SpringbatchPartitionConfig.class);
    context.refresh();

    final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    final Job job = (Job) context.getBean("partitionerJob");
    LOGGER.info("Starting the batch job");
    try {
        final JobExecution execution = jobLauncher.run(job, new JobParameters());
        LOGGER.info("Job Status : {}", execution.getStatus());
    } catch (final Exception e) {
        e.printStackTrace();
        LOGGER.error("Job failed {}", e.getMessage());
    }
}
 
Example 7
Source Project: tutorials   Source File: App.java    License: 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 8
Source Project: spring-graalvm-native   Source File: BatchConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(JobOperator.class)
public JobOperator jobOperator(ObjectProvider<JobParametersConverter> jobParametersConverter,
		JobExplorer jobExplorer, JobLauncher jobLauncher, ListableJobLocator jobRegistry,
		JobRepository jobRepository) throws Exception {
	System.out.println("FOOBAR");
	SimpleJobOperator factory = new SimpleJobOperator();
	factory.setJobExplorer(jobExplorer);
	factory.setJobLauncher(jobLauncher);
	factory.setJobRegistry(jobRegistry);
	factory.setJobRepository(jobRepository);
	jobParametersConverter.ifAvailable(factory::setJobParametersConverter);
	return factory;
}
 
Example 9
Source Project: spring-cloud   Source File: SpringBatchConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private JobLauncher createJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}
 
Example 10
@Bean
@ConditionalOnMissingBean
FlowRunner flowRunner(StepBuilderFactory stepBuilderFactory,
		JobBuilderFactory jobBuilderFactory,
		ProjectsToRunFactory projectsToRunFactory, JobLauncher jobLauncher,
		FlowRunnerTaskExecutorSupplier flowRunnerTaskExecutorSupplier,
		ConfigurableApplicationContext context, ReleaserProperties releaserProperties,
		BuildReportHandler reportHandler) {
	return new SpringBatchFlowRunner(stepBuilderFactory, jobBuilderFactory,
			projectsToRunFactory, jobLauncher, flowRunnerTaskExecutorSupplier,
			context, releaserProperties, reportHandler);
}
 
Example 11
Source Project: messaging   Source File: EtlFlowConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
IntegrationFlow etlFlow(
 @Value("${input-directory:${HOME}/Desktop/in}") File directory,
 BatchChannels c, JobLauncher launcher, Job job) {

 return IntegrationFlows
  .from(Files.inboundAdapter(directory).autoCreateDirectory(true),
   cs -> cs.poller(p -> p.fixedRate(1000)))
  .handle(
   File.class,
   (file, headers) -> {

    String absolutePath = file.getAbsolutePath();
	 	 // <2>
    JobParameters params = new JobParametersBuilder().addString("file",
     absolutePath).toJobParameters();

    return MessageBuilder.withPayload(new JobLaunchRequest(job, params))
     .setHeader(ORIGINAL_FILE, absolutePath)
     .copyHeadersIfAbsent(headers).build();
   })
 // <3>
  .handle(new JobLaunchingGateway(launcher))
 // <4>
  .routeToRecipients(
   spec -> spec.recipient(c.invalid(), this::notFinished).recipient(
    c.completed(), this::finished)).get();
}
 
Example 12
@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 13
Source Project: spring-batch-lightmin   Source File: AbstractScheduler.java    License: Apache License 2.0 5 votes vote down vote up
JobRunner(final Job job, final JobLauncher jobLauncher,
          final JobParameters jobParameters,
          final JobIncrementer jobIncrementer) {
    this.job = job;
    this.jobLauncher = jobLauncher;
    this.jobParameters = jobParameters;
    this.jobIncrementer = jobIncrementer;
}
 
Example 14
Source Project: spring-batch-lightmin   Source File: BeanRegistrarIT.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    this.applicationContext = new AnnotationConfigApplicationContext(ITConfiguration.class);
    this.beanRegistrar = this.applicationContext.getBean(BeanRegistrar.class);
    this.simpleJob = this.applicationContext.getBean("simpleJob", Job.class);
    this.jobLauncher = this.applicationContext.getBean("jobLauncher", JobLauncher.class);
}
 
Example 15
Source Project: spring-batch-lightmin   Source File: JobLauncherBean.java    License: Apache License 2.0 5 votes vote down vote up
public JobLauncherBean(final JobLauncher jobLauncher,
                       final JobRegistry jobRegistry,
                       final SpringBatchLightminCoreConfigurationProperties properties) {
    this.jobLauncher = jobLauncher;
    this.JobRegistry = jobRegistry;
    this.springBatchLightminCoreConfigurationProperties = properties;
}
 
Example 16
private String registerFolderListener(final JobConfiguration jobConfiguration) {
    final String beanName;
    try {
        final ListenerConstructorWrapper listenerConstructorWrapper = new ListenerConstructorWrapper();
        final JobListenerConfiguration jobListenerConfiguration = jobConfiguration.getJobListenerConfiguration();
        final JobLauncher jobLauncher = this.createLobLauncher(jobListenerConfiguration.getTaskExecutorType(), this.jobRepository);
        final JobParameters jobParameters = ServiceUtil.mapToJobParameters(jobConfiguration.getJobParameters());
        final Job job = this.jobRegistry.getJob(jobConfiguration.getJobName());
        listenerConstructorWrapper.setJob(job);
        listenerConstructorWrapper.setJobParameters(jobParameters);
        listenerConstructorWrapper.setJobLauncher(jobLauncher);
        listenerConstructorWrapper.setJobConfiguration(jobConfiguration);
        listenerConstructorWrapper.setJobIncrementer(jobConfiguration.getJobIncrementer());
        if (!StringUtils.hasText(jobListenerConfiguration.getBeanName())) {
            beanName = this.generateSchedulerBeanName(jobConfiguration.getJobName(),
                    jobListenerConfiguration.getJobListenerType());
        } else {
            beanName = jobListenerConfiguration.getBeanName();
        }
        final Set<Object> constructorValues = new HashSet<>();
        constructorValues.add(listenerConstructorWrapper);
        this.beanRegistrar.registerBean(FolderListener.class, beanName, constructorValues, null, null, null, null);
    } catch (final Exception e) {
        throw new SpringBatchLightminConfigurationException(e, e.getMessage());
    }
    return beanName;
}
 
Example 17
private String registerScheduler(final JobConfiguration jobConfiguration, final Class<?> schedulerClass) {
    try {
        final Set<Object> constructorValues = new HashSet<>();
        final JobLauncher jobLauncher = this.createLobLauncher(
                jobConfiguration.getJobSchedulerConfiguration().getTaskExecutorType(),
                this.jobRepository);
        final Job job = this.jobRegistry.getJob(jobConfiguration.getJobName());
        final JobParameters jobParameters = ServiceUtil.mapToJobParameters(jobConfiguration.getJobParameters());
        final JobSchedulerConfiguration jobSchedulerConfiguration = jobConfiguration.getJobSchedulerConfiguration();
        final String beanName;
        if (jobSchedulerConfiguration.getBeanName() == null || jobSchedulerConfiguration.getBeanName().isEmpty()) {
            beanName = this.generateSchedulerBeanName(jobConfiguration.getJobName(),
                    jobConfiguration.getJobSchedulerConfiguration().getJobSchedulerType());
        } else {
            beanName = jobSchedulerConfiguration.getBeanName();
        }
        final ThreadPoolTaskScheduler threadPoolTaskScheduler = this.registerThreadPoolTaskScheduler(beanName);
        final SchedulerConstructorWrapper schedulerConstructorWrapper = new SchedulerConstructorWrapper();
        schedulerConstructorWrapper.setJobParameters(jobParameters);
        schedulerConstructorWrapper.setJob(job);
        schedulerConstructorWrapper.setJobLauncher(jobLauncher);
        schedulerConstructorWrapper.setJobIncrementer(jobConfiguration.getJobIncrementer());
        schedulerConstructorWrapper.setJobConfiguration(jobConfiguration);
        schedulerConstructorWrapper.setThreadPoolTaskScheduler(threadPoolTaskScheduler);
        constructorValues.add(schedulerConstructorWrapper);
        this.beanRegistrar.registerBean(
                schedulerClass,
                beanName,
                constructorValues,
                null,
                null,
                null,
                null);
        return beanName;
    } catch (final Exception e) {
        throw new SpringBatchLightminConfigurationException(e, e.getMessage());
    }
}
 
Example 18
@Bean
@ConditionalOnMissingBean(value = {JobLauncherBean.class})
public JobLauncherBean jobLauncherBean(
        @Qualifier("defaultAsyncJobLauncher") final JobLauncher defaultAsyncJobLauncher,
        final JobRegistry jobRegistry,
        final SpringBatchLightminCoreConfigurationProperties properties) {

    return new JobLauncherBean(defaultAsyncJobLauncher, jobRegistry, properties);
}
 
Example 19
@Bean
public JobLauncherBean jobLauncherBean(
        @Qualifier("defaultAsyncJobLauncher") final JobLauncher defaultAsyncJobLauncher,
        final JobRegistry jobRegistry,
        final SpringBatchLightminCoreConfigurationProperties properties) {
    return new JobLauncherBean(defaultAsyncJobLauncher, jobRegistry, properties);
}
 
Example 20
@Bean(name = "defaultAsyncJobLauncher")
public JobLauncher defaultAsyncJobLauncher(final JobRepository jobRepository) {
    final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
    return jobLauncher;
}
 
Example 21
@Test
public void testSimpleConfiguration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(SimpleConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1",
					"spring.batch.job.chunkSize=5");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		ListItemWriter itemWriter = context.getBean(ListItemWriter.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		List<Map<Object, Object>> writtenItems = itemWriter.getWrittenItems();

		assertThat(writtenItems.size()).isEqualTo(3);

		assertThat(writtenItems.get(0).get("item")).isEqualTo("foo");
		assertThat(writtenItems.get(1).get("item")).isEqualTo("bar");
		assertThat(writtenItems.get(2).get("item")).isEqualTo("baz");
	});
}
 
Example 22
@Test
public void testCustomLineMapper() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(CustomLineMapperConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemReaderAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilereader.name=fixedWidthConfiguration",
					"spring.batch.job.flatfilereader.resource=/test.txt",
					"spring.batch.job.flatfilereader.strict=true");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		ListItemWriter itemWriter = context.getBean(ListItemWriter.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		List writtenItems = itemWriter.getWrittenItems();

		assertThat(writtenItems.size()).isEqualTo(8);
	});
}
 
Example 23
@Test
public void testCustomMapping() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(CustomMappingConfiguration.class)
			.withConfiguration(AutoConfigurations.of(
					PropertyPlaceholderAutoConfiguration.class,
					BatchAutoConfiguration.class,
					SingleStepJobAutoConfiguration.class,
					FlatFileItemReaderAutoConfiguration.class, RangeConverter.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilereader.name=fixedWidthConfiguration",
					"spring.batch.job.flatfilereader.resource=/test.txt",
					"spring.batch.job.flatfilereader.maxItemCount=1",
					"spring.batch.job.flatfilereader.strict=true");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		ListItemWriter itemWriter = context.getBean(ListItemWriter.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		List<Map<Object, Object>> writtenItems = itemWriter.getWrittenItems();

		assertThat(writtenItems.size()).isEqualTo(1);
		assertThat(writtenItems.get(0).get("one")).isEqualTo("1 2 3");
		assertThat(writtenItems.get(0).get("two")).isEqualTo("4 5 six");
	});
}
 
Example 24
@Test
public void testFormattedFieldExtractorFileGeneration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(FormattedFieldExtractorJobConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemWriterAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilewriter.name=fooWriter",
					String.format(
							"spring.batch.job.flatfilewriter.resource=file://%s",
							this.outputFile.getAbsolutePath()),
					"spring.batch.job.flatfilewriter.encoding=UTF-8",
					"spring.batch.job.flatfilewriter.formatted=true",
					"spring.batch.job.flatfilewriter.names=item",
					"spring.batch.job.flatfilewriter.format=item = %s");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		AssertFile.assertLineCount(3, this.outputFile);

		String results = FileCopyUtils.copyToString(new InputStreamReader(
				new FileSystemResource(this.outputFile).getInputStream()));
		assertThat(results).isEqualTo("item = f\nitem = b\nitem = b\n");
	});
}
 
Example 25
@Test
public void testFieldExtractorFileGeneration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(FieldExtractorConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemWriterAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilewriter.name=fooWriter",
					String.format(
							"spring.batch.job.flatfilewriter.resource=file://%s",
							this.outputFile.getAbsolutePath()),
					"spring.batch.job.flatfilewriter.encoding=UTF-8",
					"spring.batch.job.flatfilewriter.delimited=true");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		AssertFile.assertLineCount(3, this.outputFile);

		String results = FileCopyUtils.copyToString(new InputStreamReader(
				new FileSystemResource(this.outputFile).getInputStream()));
		assertThat(results).isEqualTo("f\nb\nb\n");
	});
}
 
Example 26
@Test
public void testCustomLineAggregatorFileGeneration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(LineAggregatorConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemWriterAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilewriter.name=fooWriter",
					String.format(
							"spring.batch.job.flatfilewriter.resource=file://%s",
							this.outputFile.getAbsolutePath()),
					"spring.batch.job.flatfilewriter.encoding=UTF-8");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		AssertFile.assertLineCount(3, this.outputFile);

		String results = FileCopyUtils.copyToString(new InputStreamReader(
				new FileSystemResource(this.outputFile).getInputStream()));
		assertThat(results).isEqualTo("{item=foo}\n{item=bar}\n{item=baz}\n");
	});
}
 
Example 27
@Test
public void testHeaderFooterFileGeneration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(HeaderFooterConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemWriterAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilewriter.name=fooWriter",
					String.format(
							"spring.batch.job.flatfilewriter.resource=file://%s",
							this.outputFile.getAbsolutePath()),
					"spring.batch.job.flatfilewriter.encoding=UTF-8",
					"spring.batch.job.flatfilewriter.delimited=true",
					"spring.batch.job.flatfilewriter.names=item");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		AssertFile.assertLineCount(5, this.outputFile);

		String results = FileCopyUtils.copyToString(new InputStreamReader(
				new FileSystemResource(this.outputFile).getInputStream()));
		assertThat(results).isEqualTo("header\nfoo\nbar\nbaz\nfooter");
	});
}
 
Example 28
/**
 * Create a new {@link TaskJobLauncherCommandLineRunner}.
 * @param jobLauncher to launch jobs
 * @param jobExplorer to check the job repository for previous executions
 * @param jobRepository to check if a job instance exists with the given parameters
 * when running a job
 * @param taskBatchProperties the properties used to configure the
 * taskBatchProperties.
 */
public TaskJobLauncherCommandLineRunner(JobLauncher jobLauncher,
		JobExplorer jobExplorer, JobRepository jobRepository,
		TaskBatchProperties taskBatchProperties) {
	super(jobLauncher, jobExplorer, jobRepository);
	this.taskJobLauncher = jobLauncher;
	this.taskJobExplorer = jobExplorer;
	this.taskJobRepository = jobRepository;
	this.taskBatchProperties = taskBatchProperties;
}
 
Example 29
@Bean
public TaskJobLauncherCommandLineRunnerFactoryBean jobLauncherCommandLineRunner(
		JobLauncher jobLauncher, JobExplorer jobExplorer, List<Job> jobs,
		JobRegistry jobRegistry, JobRepository jobRepository,
		BatchProperties batchProperties) {
	TaskJobLauncherCommandLineRunnerFactoryBean taskJobLauncherCommandLineRunnerFactoryBean;
	taskJobLauncherCommandLineRunnerFactoryBean = new TaskJobLauncherCommandLineRunnerFactoryBean(
			jobLauncher, jobExplorer, jobs, this.properties, jobRegistry,
			jobRepository, batchProperties);

	return taskJobLauncherCommandLineRunnerFactoryBean;
}
 
Example 30
@Override
public JobLauncher getJobLauncher() {
	SimpleJobLauncher launcher = new SimpleJobLauncher();
	launcher.setJobRepository(this.jobRepository);
	launcher.setTaskExecutor(new SyncTaskExecutor());
	return launcher;
}