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

The following examples show how to use org.springframework.batch.core.launch.JobLauncher. 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: QuartzJobLauncher.java    From spring-batch-rest with 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
Source File: AbstractSpringAcceptanceTests.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@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
Source File: SpringBatchFlowRunner.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
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 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 #5
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 #6
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 #7
Source File: TaskJobLauncherCommandLineRunnerFactoryBean.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: SpringbatchPartitionerApp.java    From tutorials with 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 #9
Source File: SingleStepJobAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: FlatFileItemReaderAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #11
Source File: JobRunner.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG);

	Job job = applicationContext.getBean(Job.class);
	JobLauncher jobLauncher = applicationContext.getBean(JobLauncher.class);

	jobLauncher.run(job, new JobParameters());
}
 
Example #12
Source File: JobRunner.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG);

	Job job = applicationContext.getBean(Job.class);
	JobLauncher jobLauncher = applicationContext.getBean(JobLauncher.class);

	jobLauncher.run(job, new JobParameters());
}
 
Example #13
Source File: JobRunner.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG);

	Job job = applicationContext.getBean(Job.class);
	JobLauncher jobLauncher = applicationContext.getBean(JobLauncher.class);

	jobLauncher.run(job, new JobParameters());
}
 
Example #14
Source File: SpringBatchLightminBatchConfiguration.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@Bean(name = "defaultAsyncJobLauncher")
public JobLauncher defaultAsyncJobLauncher(final JobRepository jobRepository) {
    final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
    return jobLauncher;
}
 
Example #15
Source File: JobRunner.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG);

	Job job = applicationContext.getBean(Job.class);
	JobLauncher jobLauncher = applicationContext.getBean(JobLauncher.class);

	jobLauncher.run(job, new JobParameters());
}
 
Example #16
Source File: AbstractScheduler.java    From spring-batch-lightmin with 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 #17
Source File: SpringbatchPartitionConfig.java    From tutorials with MIT License 5 votes vote down vote up
public JobLauncher getJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    // SimpleJobLauncher's methods Throws Generic Exception,
    // it would have been better to have a specific one
    jobLauncher.setJobRepository(getJobRepository());
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}
 
Example #18
Source File: EtlFlowConfiguration.java    From messaging with 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 #19
Source File: SpringConfig.java    From tutorials with MIT License 5 votes vote down vote up
public JobLauncher getJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    // SimpleJobLauncher's methods Throws Generic Exception,
    // it would have been better to have a specific one
    jobLauncher.setJobRepository(getJobRepository());
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}
 
Example #20
Source File: BatchConfiguration.java    From spring-graalvm-native with 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 #21
Source File: TaskJobLauncherCommandLineRunnerTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
protected JobLauncher createJobLauncher() throws Exception {
	SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
	jobLauncher.setJobRepository(getJobRepository());
	jobLauncher.setTaskExecutor(new ConcurrentTaskExecutor());
	jobLauncher.afterPropertiesSet();
	return jobLauncher;
}
 
Example #22
Source File: FlatFileItemReaderAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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
Source File: TaskJobLauncherCommandLineRunnerCoreTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Override
public JobLauncher getJobLauncher() {
	SimpleJobLauncher launcher = new SimpleJobLauncher();
	launcher.setJobRepository(this.jobRepository);
	launcher.setTaskExecutor(new SyncTaskExecutor());
	return launcher;
}
 
Example #24
Source File: DefaultSchedulerService.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: TaskJobLauncherAutoConfiguration.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: FlatFileItemWriterAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: FlatFileItemWriterAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: FlatFileItemWriterAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: FlatFileItemWriterAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: TaskJobLauncherCommandLineRunner.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}