diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/RangeConverter.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/RangeConverter.java index 13aa5b04..9e2da5b9 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/RangeConverter.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/RangeConverter.java @@ -51,9 +51,8 @@ public class RangeConverter implements Converter { return new Range(start, end); } else { - throw new IllegalArgumentException(String.format( - "%s is in an illegal format. Ranges must be specified as startIndex-endIndex", - source)); + throw new IllegalArgumentException(String + .format("%s is in an illegal format. Ranges must be specified as startIndex-endIndex", source)); } } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfiguration.java index e9c86fe2..fc574f7b 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfiguration.java @@ -57,9 +57,8 @@ public class SingleStepJobAutoConfiguration { @Autowired(required = false) private ItemProcessor, Map> itemProcessor; - public SingleStepJobAutoConfiguration(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, SingleStepJobProperties properties, - ApplicationContext context) { + public SingleStepJobAutoConfiguration(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, + SingleStepJobProperties properties, ApplicationContext context) { validateProperties(properties); @@ -72,27 +71,23 @@ public class SingleStepJobAutoConfiguration { Assert.hasText(properties.getJobName(), "A job name is required"); Assert.hasText(properties.getStepName(), "A step name is required"); Assert.notNull(properties.getChunkSize(), "A chunk size is required"); - Assert.isTrue(properties.getChunkSize() > 0, - "A chunk size greater than zero is required"); + Assert.isTrue(properties.getChunkSize() > 0, "A chunk size greater than zero is required"); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.batch.job", name = "job-name") - public Job job(ItemReader> itemReader, - ItemWriter> itemWriter) { + public Job job(ItemReader> itemReader, ItemWriter> itemWriter) { SimpleStepBuilder, Map> stepBuilder = this.stepBuilderFactory .get(this.properties.getStepName()) - ., Map>chunk( - this.properties.getChunkSize()) - .reader(itemReader); + ., Map>chunk(this.properties.getChunkSize()).reader(itemReader); stepBuilder.processor(this.itemProcessor); Step step = stepBuilder.writer(itemWriter).build(); - return this.jobBuilderFactory.get(this.properties.getJobName()).start(step) - .build(); + return this.jobBuilderFactory.get(this.properties.getJobName()).start(step).build(); } + } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfiguration.java index 70f64270..598e97eb 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfiguration.java @@ -58,47 +58,36 @@ public class FlatFileItemReaderAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.batch.job.flatfileitemreader", name = "name") - public FlatFileItemReader> itemReader( - @Autowired(required = false) LineTokenizer lineTokenizer, - @Autowired(required = false) FieldSetMapper> fieldSetMapper, - @Autowired(required = false) LineMapper> lineMapper, - @Autowired(required = false) LineCallbackHandler skippedLinesCallback, - @Autowired(required = false) RecordSeparatorPolicy recordSeparatorPolicy) { + public FlatFileItemReader> itemReader(@Autowired(required = false) LineTokenizer lineTokenizer, + @Autowired(required = false) FieldSetMapper> fieldSetMapper, + @Autowired(required = false) LineMapper> lineMapper, + @Autowired(required = false) LineCallbackHandler skippedLinesCallback, + @Autowired(required = false) RecordSeparatorPolicy recordSeparatorPolicy) { FlatFileItemReaderBuilder> mapFlatFileItemReaderBuilder = new FlatFileItemReaderBuilder>() .name(this.properties.getName()).resource(this.properties.getResource()) - .saveState(this.properties.isSaveState()) - .maxItemCount(this.properties.getMaxItemCount()) - .currentItemCount(this.properties.getCurrentItemCount()) - .strict(this.properties.isStrict()) - .encoding(this.properties.getEncoding()) - .linesToSkip(this.properties.getLinesToSkip()) - .comments(this.properties.getComments() - .toArray(new String[this.properties.getComments().size()])); + .saveState(this.properties.isSaveState()).maxItemCount(this.properties.getMaxItemCount()) + .currentItemCount(this.properties.getCurrentItemCount()).strict(this.properties.isStrict()) + .encoding(this.properties.getEncoding()).linesToSkip(this.properties.getLinesToSkip()) + .comments(this.properties.getComments().toArray(new String[this.properties.getComments().size()])); mapFlatFileItemReaderBuilder.lineTokenizer(lineTokenizer); if (recordSeparatorPolicy != null) { - mapFlatFileItemReaderBuilder - .recordSeparatorPolicy(recordSeparatorPolicy); + mapFlatFileItemReaderBuilder.recordSeparatorPolicy(recordSeparatorPolicy); } mapFlatFileItemReaderBuilder.fieldSetMapper(fieldSetMapper); mapFlatFileItemReaderBuilder.lineMapper(lineMapper); mapFlatFileItemReaderBuilder.skippedLinesCallback(skippedLinesCallback); if (this.properties.isDelimited()) { - mapFlatFileItemReaderBuilder.delimited() - .quoteCharacter(this.properties.getQuoteCharacter()) + mapFlatFileItemReaderBuilder.delimited().quoteCharacter(this.properties.getQuoteCharacter()) .delimiter(this.properties.getDelimiter()) - .includedFields( - this.properties.getIncludedFields().toArray(new Integer[0])) - .names(this.properties.getNames()) - .beanMapperStrict(this.properties.isParsingStrict()) + .includedFields(this.properties.getIncludedFields().toArray(new Integer[0])) + .names(this.properties.getNames()).beanMapperStrict(this.properties.isParsingStrict()) .fieldSetMapper(new MapFieldSetMapper()); } else if (this.properties.isFixedLength()) { - mapFlatFileItemReaderBuilder.fixedLength() - .columns(this.properties.getRanges().toArray(new Range[0])) - .names(this.properties.getNames()) - .fieldSetMapper(new MapFieldSetMapper()) + mapFlatFileItemReaderBuilder.fixedLength().columns(this.properties.getRanges().toArray(new Range[0])) + .names(this.properties.getNames()).fieldSetMapper(new MapFieldSetMapper()) .beanMapperStrict(this.properties.isParsingStrict()); } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderProperties.java index badfdb9e..afebe18c 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderProperties.java @@ -73,8 +73,8 @@ public class FlatFileItemReaderProperties { private boolean strict = true; /** - * Configure the encoding used by the reader to read the input source. The default value - * is {@link FlatFileItemReader#DEFAULT_CHARSET}. + * Configure the encoding used by the reader to read the input source. The default + * value is {@link FlatFileItemReader#DEFAULT_CHARSET}. */ private String encoding = FlatFileItemReader.DEFAULT_CHARSET; diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfiguration.java index aef6e922..4ba7155e 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfiguration.java @@ -71,44 +71,37 @@ public class FlatFileItemWriterAutoConfiguration { public FlatFileItemWriter> itemWriter() { if (this.properties.isDelimited() && this.properties.isFormatted()) { - throw new IllegalStateException( - "An output file must be either delimited or formatted or a custom " - + "LineAggregator must be provided. Your current configuration specifies both delimited and formatted"); + throw new IllegalStateException("An output file must be either delimited or formatted or a custom " + + "LineAggregator must be provided. Your current configuration specifies both delimited and formatted"); } - else if ((this.properties.isFormatted() || this.properties.isDelimited()) - && this.lineAggregator != null) { - throw new IllegalStateException("A LineAggregator must be configured if the " - + "output is not formatted or delimited"); + else if ((this.properties.isFormatted() || this.properties.isDelimited()) && this.lineAggregator != null) { + throw new IllegalStateException( + "A LineAggregator must be configured if the " + "output is not formatted or delimited"); } FlatFileItemWriterBuilder> builder = new FlatFileItemWriterBuilder>() .name(this.properties.getName()).resource((WritableResource) this.properties.getResource()) - .append(this.properties.isAppend()) - .encoding(this.properties.getEncoding()) - .forceSync(this.properties.isForceSync()) - .lineSeparator(this.properties.getLineSeparator()) - .saveState(this.properties.isSaveState()) - .shouldDeleteIfEmpty(this.properties.isShouldDeleteIfEmpty()) + .append(this.properties.isAppend()).encoding(this.properties.getEncoding()) + .forceSync(this.properties.isForceSync()).lineSeparator(this.properties.getLineSeparator()) + .saveState(this.properties.isSaveState()).shouldDeleteIfEmpty(this.properties.isShouldDeleteIfEmpty()) .shouldDeleteIfExists(this.properties.isShouldDeleteIfExists()) - .transactional(this.properties.isTransactional()) - .headerCallback(this.headerCallback).footerCallback(this.footerCallback); + .transactional(this.properties.isTransactional()).headerCallback(this.headerCallback) + .footerCallback(this.footerCallback); if (this.properties.isDelimited()) { - FlatFileItemWriterBuilder.DelimitedBuilder> delimitedBuilder = builder - .delimited().delimiter(this.properties.getDelimiter()); + FlatFileItemWriterBuilder.DelimitedBuilder> delimitedBuilder = builder.delimited() + .delimiter(this.properties.getDelimiter()); if (this.fieldExtractor != null) { delimitedBuilder.fieldExtractor(this.fieldExtractor); } else { - delimitedBuilder.fieldExtractor( - new MapFieldExtractor(this.properties.getNames())); + delimitedBuilder.fieldExtractor(new MapFieldExtractor(this.properties.getNames())); } } else if (this.properties.isFormatted()) { - FlatFileItemWriterBuilder.FormattedBuilder> formattedBuilder = builder - .formatted().format(this.properties.getFormat()) - .locale(this.properties.getLocale()) + FlatFileItemWriterBuilder.FormattedBuilder> formattedBuilder = builder.formatted() + .format(this.properties.getFormat()).locale(this.properties.getLocale()) .maximumLength(this.properties.getMaximumLength()) .minimumLength(this.properties.getMinimumLength()); @@ -116,8 +109,7 @@ public class FlatFileItemWriterAutoConfiguration { formattedBuilder.fieldExtractor(this.fieldExtractor); } else { - formattedBuilder.fieldExtractor( - new MapFieldExtractor(this.properties.getNames())); + formattedBuilder.fieldExtractor(new MapFieldExtractor(this.properties.getNames())); } } else if (this.lineAggregator != null) { diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterProperties.java index 39f7191f..474d6a5c 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterProperties.java @@ -37,8 +37,8 @@ public class FlatFileItemWriterProperties { private Resource resource; /** - * Configure the use of the {@code DelimitedLineAggregator} to generate the output per item. - * Default is {@code false}. + * Configure the use of the {@code DelimitedLineAggregator} to generate the output per + * item. Default is {@code false}. */ private boolean delimited; @@ -65,7 +65,7 @@ public class FlatFileItemWriterProperties { /** * Configure the minimum record length. - */ + */ private int minimumLength = 0; /** @@ -74,12 +74,14 @@ public class FlatFileItemWriterProperties { private String delimiter = ","; /** - * File encoding for the output file. Defaults to {@code FlatFileItemWriter.DEFAULT_CHARSET}) + * File encoding for the output file. Defaults to + * {@code FlatFileItemWriter.DEFAULT_CHARSET}) */ private String encoding = FlatFileItemWriter.DEFAULT_CHARSET; /** - * A flag indicating that changes should be force-synced to disk on flush. Defaults to {@code false}. + * A flag indicating that changes should be force-synced to disk on flush. Defaults to + * {@code false}. */ private boolean forceSync = false; @@ -89,12 +91,14 @@ public class FlatFileItemWriterProperties { private String[] names; /** - * Configure if the output file is found if it should be appended to. Defaults to {@code false}. + * Configure if the output file is found if it should be appended to. Defaults to + * {@code false}. */ private boolean append = false; /** - * String used to separate lines in output. Defaults to the {@code System} property {@code line.separator}. + * String used to separate lines in output. Defaults to the {@code System} property + * {@code line.separator}. */ private String lineSeparator = FlatFileItemWriter.DEFAULT_LINE_SEPARATOR; @@ -117,12 +121,14 @@ public class FlatFileItemWriterProperties { private boolean shouldDeleteIfEmpty = false; /** - * Indicates whether an existing output file should be deleted on startup. Defaults to {@code true}. + * Indicates whether an existing output file should be deleted on startup. Defaults to + * {@code true}. */ private boolean shouldDeleteIfExists = true; /** - * Indicates whether flushing the buffer should be delayed while a transaction is active. Defaults to {@code true}. + * Indicates whether flushing the buffer should be delayed while a transaction is + * active. Defaults to {@code true}. */ private boolean transactional = FlatFileItemWriter.DEFAULT_TRANSACTIONAL; diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JDBCSingleStepDataSourceAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JDBCSingleStepDataSourceAutoConfiguration.java index fa259d2c..3b583a47 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JDBCSingleStepDataSourceAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JDBCSingleStepDataSourceAutoConfiguration.java @@ -29,9 +29,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; /** - * Establishes the default {@link DataSource} for the Task when creating a {@link DataSource} - * for {@link org.springframework.batch.item.database.JdbcCursorItemReader} - * or {@link org.springframework.batch.item.database.JdbcBatchItemWriter}. + * Establishes the default {@link DataSource} for the Task when creating a + * {@link DataSource} for + * {@link org.springframework.batch.item.database.JdbcCursorItemReader} or + * {@link org.springframework.batch.item.database.JdbcBatchItemWriter}. * * @author Glenn Renfro * @since 3.0 @@ -44,7 +45,8 @@ class JDBCSingleStepDataSourceAutoConfiguration { return new DefaultTaskConfigurer(dataSource); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbcsinglestep.datasource", name = "enable", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.batch.job.jdbcsinglestep.datasource", name = "enable", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(name = "springDataSourceProperties") @Bean(name = "springDataSourceProperties") @ConfigurationProperties("spring.datasource") @@ -53,11 +55,14 @@ class JDBCSingleStepDataSourceAutoConfiguration { return new DataSourceProperties(); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbcsinglestep.datasource", name = "enable", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.batch.job.jdbcsinglestep.datasource", name = "enable", havingValue = "true", + matchIfMissing = true) @Bean(name = "springDataSource") @Primary - public DataSource dataSource(@Qualifier("springDataSourceProperties")DataSourceProperties springDataSourceProperties) { - DataSource dataSource = springDataSourceProperties.initializeDataSourceBuilder().build(); + public DataSource dataSource( + @Qualifier("springDataSourceProperties") DataSourceProperties springDataSourceProperties) { + DataSource dataSource = springDataSourceProperties.initializeDataSourceBuilder().build(); return dataSource; } + } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfiguration.java index cbb53318..5f1a5611 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfiguration.java @@ -54,8 +54,7 @@ import org.springframework.context.annotation.Import; @Import(JDBCSingleStepDataSourceAutoConfiguration.class) public class JdbcBatchItemWriterAutoConfiguration { - private static final Log logger = LogFactory - .getLog(JdbcBatchItemWriterAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(JdbcBatchItemWriterAutoConfiguration.class); @Autowired(required = false) private ItemPreparedStatementSetter itemPreparedStatementSetter; @@ -70,8 +69,7 @@ public class JdbcBatchItemWriterAutoConfiguration { private DataSource dataSource; - public JdbcBatchItemWriterAutoConfiguration(DataSource dataSource, - JdbcBatchItemWriterProperties properties) { + public JdbcBatchItemWriterAutoConfiguration(DataSource dataSource, JdbcBatchItemWriterProperties properties) { this.dataSource = dataSource; this.properties = properties; } @@ -91,12 +89,10 @@ public class JdbcBatchItemWriterAutoConfiguration { JdbcBatchItemWriterBuilder> jdbcBatchItemWriterBuilder = new JdbcBatchItemWriterBuilder>() .dataSource(writerDataSource).sql(this.properties.getSql()); if (this.itemPreparedStatementSetter != null) { - jdbcBatchItemWriterBuilder - .itemPreparedStatementSetter(this.itemPreparedStatementSetter); + jdbcBatchItemWriterBuilder.itemPreparedStatementSetter(this.itemPreparedStatementSetter); } else if (this.itemSqlParameterSourceProvider != null) { - jdbcBatchItemWriterBuilder - .itemSqlParameterSourceProvider(this.itemSqlParameterSourceProvider); + jdbcBatchItemWriterBuilder.itemSqlParameterSourceProvider(this.itemSqlParameterSourceProvider); } else { jdbcBatchItemWriterBuilder.columnMapped(); @@ -105,17 +101,21 @@ public class JdbcBatchItemWriterAutoConfiguration { return jdbcBatchItemWriterBuilder.build(); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbcbatchitemwriter.datasource", name = "enable", havingValue = "true") + @ConditionalOnProperty(prefix = "spring.batch.job.jdbcbatchitemwriter.datasource", name = "enable", + havingValue = "true") @Bean(name = "jdbcBatchItemWriterDataSourceProperties") @ConfigurationProperties("jdbcbatchitemwriter.datasource") public DataSourceProperties jdbcBatchItemWriterDataSourceProperties() { return new DataSourceProperties(); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbcbatchitemwriter.datasource", name = "enable", havingValue = "true") + @ConditionalOnProperty(prefix = "spring.batch.job.jdbcbatchitemwriter.datasource", name = "enable", + havingValue = "true") @Bean(name = "jdbcBatchItemWriterSpringDataSource") - public DataSource writerDataSource(@Qualifier("jdbcBatchItemWriterDataSourceProperties") DataSourceProperties writerDataSourceProperties) { - DataSource result = writerDataSourceProperties.initializeDataSourceBuilder().build(); + public DataSource writerDataSource( + @Qualifier("jdbcBatchItemWriterDataSourceProperties") DataSourceProperties writerDataSourceProperties) { + DataSource result = writerDataSourceProperties.initializeDataSourceBuilder().build(); return result; } + } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterProperties.java index c213a0c7..91d03edb 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterProperties.java @@ -39,8 +39,8 @@ public class JdbcBatchItemWriterProperties { private String sql; /** - * If set to {@code true}, confirms that every insert results in the update of at least one - * row in the database. Defaults to {@code true}. + * If set to {@code true}, confirms that every insert results in the update of at + * least one row in the database. Defaults to {@code true}. */ private boolean assertUpdates = true; diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfiguration.java index fa5c3eb6..9b99e4f0 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfiguration.java @@ -56,8 +56,7 @@ import org.springframework.jdbc.core.RowMapper; @Import(JDBCSingleStepDataSourceAutoConfiguration.class) public class JdbcCursorItemReaderAutoConfiguration { - private static final Log logger = LogFactory - .getLog(JdbcCursorItemReaderAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(JdbcCursorItemReaderAutoConfiguration.class); @Autowired ApplicationContext applicationContext; @@ -66,41 +65,34 @@ public class JdbcCursorItemReaderAutoConfiguration { private final DataSource dataSource; - public JdbcCursorItemReaderAutoConfiguration( - JdbcCursorItemReaderProperties properties, DataSource dataSource) { + public JdbcCursorItemReaderAutoConfiguration(JdbcCursorItemReaderProperties properties, DataSource dataSource) { this.properties = properties; this.dataSource = dataSource; } @Bean @ConditionalOnMissingBean - public JdbcCursorItemReader> itemReader(@Autowired(required = false) RowMapper> rowMapper, - @Autowired(required = false) PreparedStatementSetter preparedStatementSetter) { + public JdbcCursorItemReader> itemReader( + @Autowired(required = false) RowMapper> rowMapper, + @Autowired(required = false) PreparedStatementSetter preparedStatementSetter) { DataSource readerDataSource = this.dataSource; try { - readerDataSource = this.applicationContext.getBean("jdbcCursorItemReaderSpringDataSource", DataSource.class); + readerDataSource = this.applicationContext.getBean("jdbcCursorItemReaderSpringDataSource", + DataSource.class); } catch (Exception e) { logger.info("Using Default Data Source for the JdbcCursorItemReader"); } - return new JdbcCursorItemReaderBuilder>() - .name(this.properties.getName()) - .currentItemCount(this.properties.getCurrentItemCount()) - .dataSource(readerDataSource) + return new JdbcCursorItemReaderBuilder>().name(this.properties.getName()) + .currentItemCount(this.properties.getCurrentItemCount()).dataSource(readerDataSource) .driverSupportsAbsolute(this.properties.isDriverSupportsAbsolute()) - .fetchSize(this.properties.getFetchSize()) - .ignoreWarnings(this.properties.isIgnoreWarnings()) - .maxItemCount(this.properties.getMaxItemCount()) - .maxRows(this.properties.getMaxRows()) - .queryTimeout(this.properties.getQueryTimeout()) - .saveState(this.properties.isSaveState()).sql(this.properties.getSql()) - .rowMapper(rowMapper) - .preparedStatementSetter(preparedStatementSetter) + .fetchSize(this.properties.getFetchSize()).ignoreWarnings(this.properties.isIgnoreWarnings()) + .maxItemCount(this.properties.getMaxItemCount()).maxRows(this.properties.getMaxRows()) + .queryTimeout(this.properties.getQueryTimeout()).saveState(this.properties.isSaveState()) + .sql(this.properties.getSql()).rowMapper(rowMapper).preparedStatementSetter(preparedStatementSetter) .verifyCursorPosition(this.properties.isVerifyCursorPosition()) - .useSharedExtendedConnection( - this.properties.isUseSharedExtendedConnection()) - .build(); + .useSharedExtendedConnection(this.properties.isUseSharedExtendedConnection()).build(); } @Bean @@ -109,16 +101,19 @@ public class JdbcCursorItemReaderAutoConfiguration { return new MapRowMapper(); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbccursoritemreader.datasource", name = "enable", havingValue = "true") + @ConditionalOnProperty(prefix = "spring.batch.job.jdbccursoritemreader.datasource", name = "enable", + havingValue = "true") @Bean(name = "jdbcCursorItemReaderDataSourceProperties") @ConfigurationProperties("jdbccursoritemreader.datasource") public DataSourceProperties jdbcCursorItemReaderDataSourceProperties() { return new DataSourceProperties(); } - @ConditionalOnProperty(prefix = "spring.batch.job.jdbccursoritemreader.datasource", name = "enable", havingValue = "true") + @ConditionalOnProperty(prefix = "spring.batch.job.jdbccursoritemreader.datasource", name = "enable", + havingValue = "true") @Bean(name = "jdbcCursorItemReaderSpringDataSource") - public DataSource readerDataSource(@Qualifier("jdbcCursorItemReaderDataSourceProperties")DataSourceProperties readerDataSourceProperties) { + public DataSource readerDataSource( + @Qualifier("jdbcCursorItemReaderDataSourceProperties") DataSourceProperties readerDataSourceProperties) { DataSource result = readerDataSourceProperties.initializeDataSourceBuilder().build(); return result; } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderProperties.java index 41c67319..baa8545f 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderProperties.java @@ -27,14 +27,15 @@ public class JdbcCursorItemReaderProperties { /** * Configure whether the state of the - * {@link org.springframework.batch.item.ItemStreamSupport} should be persisted - * within the {@link org.springframework.batch.item.ExecutionContext} for - * restart purposes. Defaults to {@code true}. + * {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within + * the {@link org.springframework.batch.item.ExecutionContext} for restart purposes. + * Defaults to {@code true}. */ private boolean saveState = true; /** - * Returns the configured value of the name used to calculate {@code ExecutionContext} keys. + * Returns the configured value of the name used to calculate {@code ExecutionContext} + * keys. */ private String name; @@ -83,8 +84,8 @@ public class JdbcCursorItemReaderProperties { /** * Establishes whether the connection used for the cursor is being used by all other - * processing and is, therefore, part of the same transaction. - * Defaults to {@code false} + * processing and is, therefore, part of the same transaction. Defaults to + * {@code false} */ private boolean useSharedExtendedConnection; diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfiguration.java index df8f8d1c..34e0013c 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfiguration.java @@ -64,11 +64,9 @@ public class KafkaItemReaderAutoConfiguration { kafkaItemReaderProperties.getPartitions().add(0); } return new KafkaItemReaderBuilder>() - .partitions(kafkaItemReaderProperties.getPartitions()) - .consumerProperties(consumerProperties) + .partitions(kafkaItemReaderProperties.getPartitions()).consumerProperties(consumerProperties) .name(kafkaItemReaderProperties.getName()) - .pollTimeout(Duration - .ofSeconds(kafkaItemReaderProperties.getPollTimeOutInSeconds())) + .pollTimeout(Duration.ofSeconds(kafkaItemReaderProperties.getPollTimeOutInSeconds())) .saveState(kafkaItemReaderProperties.isSaveState()).topic(kafkaItemReaderProperties.getTopic()).build(); } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderProperties.java index 44ea9ca8..70adbe06 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderProperties.java @@ -48,14 +48,16 @@ public class KafkaItemReaderProperties { private List partitions = new ArrayList<>(); /** - * Establish the {@code pollTimeout} for the {@code poll()} operations. Defaults to 30 seconds. + * Establish the {@code pollTimeout} for the {@code poll()} operations. Defaults to 30 + * seconds. */ private long pollTimeOutInSeconds = 30L; /** - * Configure whether the state of the {@link org.springframework.batch.item.ItemStreamSupport} - * should be persisted within the {@link org.springframework.batch.item.ExecutionContext} - * for restart purposes. Defaults to {@code true}. + * Configure whether the state of the + * {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within + * the {@link org.springframework.batch.item.ExecutionContext} for restart purposes. + * Defaults to {@code true}. */ private boolean saveState = true; @@ -127,10 +129,12 @@ public class KafkaItemReaderProperties { public void setPollTimeOutInSeconds(long pollTimeOutInSeconds) { this.pollTimeOutInSeconds = pollTimeOutInSeconds; } + /** - * Configure if the state of the {@link org.springframework.batch.item.ItemStreamSupport} - * should be persisted within the {@link org.springframework.batch.item.ExecutionContext} - * for restart purposes. Defaults to true. + * Configure if the state of the + * {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within + * the {@link org.springframework.batch.item.ExecutionContext} for restart purposes. + * Defaults to true. * @return current status of the saveState flag. */ public boolean isSaveState() { @@ -138,12 +142,13 @@ public class KafkaItemReaderProperties { } /** - * Configure if the state of the {@link org.springframework.batch.item.ItemStreamSupport} - * should be persisted within the {@link org.springframework.batch.item.ExecutionContext} - * for restart purposes. - * @param saveState true if state should be persisted. Defaults to true. + * Configure if the state of the + * {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within + * the {@link org.springframework.batch.item.ExecutionContext} for restart purposes. + * @param saveState true if state should be persisted. Defaults to true. */ public void setSaveState(boolean saveState) { this.saveState = saveState; } + } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterAutoConfiguration.java index ce46f336..b68e4dcd 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterAutoConfiguration.java @@ -65,9 +65,8 @@ public class KafkaItemWriterAutoConfiguration { validateProperties(kafkaItemWriterProperties); KafkaTemplate template = new KafkaTemplate(producerFactory); template.setDefaultTopic(kafkaItemWriterProperties.getTopic()); - return new KafkaItemWriterBuilder>() - .delete(kafkaItemWriterProperties.isDelete()).kafkaTemplate(template) - .itemKeyMapper(itemKeyMapper).build(); + return new KafkaItemWriterBuilder>().delete(kafkaItemWriterProperties.isDelete()) + .kafkaTemplate(template).itemKeyMapper(itemKeyMapper).build(); } @Bean @@ -86,13 +85,11 @@ public class KafkaItemWriterAutoConfiguration { ProducerFactory> producerFactory() { Map configs = new HashMap<>(); configs.putAll(this.kafkaProperties.getProducer().buildProperties()); - return new DefaultKafkaProducerFactory<>(configs, null, - new JsonSerializer<>()); + return new DefaultKafkaProducerFactory<>(configs, null, new JsonSerializer<>()); } private void validateProperties(KafkaItemWriterProperties kafkaItemWriterProperties) { - Assert.hasText(kafkaItemWriterProperties.getTopic(), - "topic must not be empty or null"); + Assert.hasText(kafkaItemWriterProperties.getTopic(), "topic must not be empty or null"); } } diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfiguration.java index 3c6630e5..c917500a 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(AmqpItemReaderProperties.class) @AutoConfigureAfter(BatchAutoConfiguration.class) -@ConditionalOnProperty(name = "spring.batch.job.amqpitemreader.enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(name = "spring.batch.job.amqpitemreader.enabled", havingValue = "true", matchIfMissing = false) public class AmqpItemReaderAutoConfiguration { @Autowired(required = false) @@ -65,8 +64,8 @@ public class AmqpItemReaderAutoConfiguration { return builder.build(); } - @ConditionalOnProperty(name = "spring.batch.job.amqpitemreader.jsonConverterEnabled", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.batch.job.amqpitemreader.jsonConverterEnabled", havingValue = "true", + matchIfMissing = true) @Bean public MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfiguration.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfiguration.java index 446db096..96022062 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfiguration.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfiguration.java @@ -40,14 +40,12 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(AmqpItemWriterProperties.class) @AutoConfigureAfter(BatchAutoConfiguration.class) -@ConditionalOnProperty(name = "spring.batch.job.amqpitemwriter.enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(name = "spring.batch.job.amqpitemwriter.enabled", havingValue = "true", matchIfMissing = false) public class AmqpItemWriterAutoConfiguration { @Bean public AmqpItemWriter> amqpItemWriter(AmqpTemplate amqpTemplate) { - return new AmqpItemWriterBuilder>().amqpTemplate(amqpTemplate) - .build(); + return new AmqpItemWriterBuilder>().amqpTemplate(amqpTemplate).build(); } @Bean @@ -55,8 +53,8 @@ public class AmqpItemWriterAutoConfiguration { return new AmqpItemWriterProperties(); } - @ConditionalOnProperty(name = "spring.batch.job.amqpitemwriter.jsonConverterEnabled", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.batch.job.amqpitemwriter.jsonConverterEnabled", havingValue = "true", + matchIfMissing = true) @Bean public MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); diff --git a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterProperties.java b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterProperties.java index 418c681c..558d95ab 100644 --- a/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterProperties.java +++ b/spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterProperties.java @@ -47,7 +47,8 @@ public class AmqpItemWriterProperties { /** * Enables or disables the {@code AmqpItemWriter}. - * @param enabled if {@code true} then {@code AmqpItemWriter} is enabled. Defaults to {@code false}. + * @param enabled if {@code true} then {@code AmqpItemWriter} is enabled. Defaults to + * {@code false}. */ public void setEnabled(boolean enabled) { this.enabled = enabled; diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfigurationTests.java index 530c3917..1d534ef4 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/SingleStepJobAutoConfigurationTests.java @@ -91,8 +91,7 @@ public class SingleStepJobAutoConfigurationTests { new SingleStepJobAutoConfiguration(null, null, properties, null); } catch (IllegalArgumentException iae) { - assertThat(iae.getMessage()) - .isEqualTo("A chunk size greater than zero is required"); + assertThat(iae.getMessage()).isEqualTo("A chunk size greater than zero is required"); } catch (Throwable t) { fail("wrong exception was thrown", t); @@ -106,12 +105,9 @@ public class SingleStepJobAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(SimpleConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5"); validateConfiguration(applicationContextRunner); @@ -120,17 +116,14 @@ public class SingleStepJobAutoConfigurationTests { @Test public void testSimpleConfigurationKabobStyle() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration(SimpleConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.job-name=job", - "spring.batch.job.step-name=step1", - "spring.batch.job.chunk-size=5"); + .withUserConfiguration(SimpleConfiguration.class) + .withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.job-name=job", "spring.batch.job.step-name=step1", + "spring.batch.job.chunk-size=5"); - validateConfiguration(applicationContextRunner); + validateConfiguration(applicationContextRunner); } private void validateConfiguration(ApplicationContextRunner applicationContextRunner) { diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfigurationTests.java index f5f5ae62..d05e2208 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfigurationTests.java @@ -76,15 +76,11 @@ public class FlatFileItemReaderAutoConfigurationTests { public void testFullDelimitedConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(JobConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemreader.savestate=true", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemreader.savestate=true", "spring.batch.job.flatfileitemreader.name=fullDelimitedConfiguration", "spring.batch.job.flatfileitemreader.maxItemCount=5", "spring.batch.job.flatfileitemreader.currentItemCount=2", @@ -134,15 +130,12 @@ public class FlatFileItemReaderAutoConfigurationTests { public void testFixedWidthConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(JobConfiguration.class) - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemReaderAutoConfiguration.class, RangeConverter.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemreader.savestate=true", + .withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, FlatFileItemReaderAutoConfiguration.class, + RangeConverter.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemreader.savestate=true", "spring.batch.job.flatfileitemreader.name=fixedWidthConfiguration", "spring.batch.job.flatfileitemreader.comments=#,$", "spring.batch.job.flatfileitemreader.resource=/test.txt", @@ -195,14 +188,11 @@ public class FlatFileItemReaderAutoConfigurationTests { public void testCustomLineMapper() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomLineMapperConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemreader.name=fixedWidthConfiguration", "spring.batch.job.flatfileitemreader.resource=/test.txt", "spring.batch.job.flatfileitemreader.strict=true"); @@ -234,16 +224,13 @@ public class FlatFileItemReaderAutoConfigurationTests { @Test public void testCustomRecordSeparatorAndSkippedLines() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - RecordSeparatorAndSkippedLinesJobConfiguration.class) - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemReaderAutoConfiguration.class, RangeConverter.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", + .withUserConfiguration(RecordSeparatorAndSkippedLinesJobConfiguration.class) + .withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, FlatFileItemReaderAutoConfiguration.class, + RangeConverter.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemreader.name=fixedWidthConfiguration", "spring.batch.job.flatfileitemreader.resource=/test.txt", "spring.batch.job.flatfileitemreader.linesToSkip=2", @@ -267,8 +254,7 @@ public class FlatFileItemReaderAutoConfigurationTests { Thread.sleep(1000); } - ListLineCallbackHandler callbackHandler = context - .getBean(ListLineCallbackHandler.class); + ListLineCallbackHandler callbackHandler = context.getBean(ListLineCallbackHandler.class); assertThat(callbackHandler.getLines().size()).isEqualTo(2); @@ -282,14 +268,12 @@ public class FlatFileItemReaderAutoConfigurationTests { public void testCustomMapping() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomMappingConfiguration.class) - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemReaderAutoConfiguration.class, RangeConverter.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", + .withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, FlatFileItemReaderAutoConfiguration.class, + RangeConverter.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemreader.name=fixedWidthConfiguration", "spring.batch.job.flatfileitemreader.resource=/test.txt", "spring.batch.job.flatfileitemreader.maxItemCount=1", @@ -329,8 +313,7 @@ public class FlatFileItemReaderAutoConfigurationTests { @Bean public LineTokenizer lineTokenizer() { - return line -> new DefaultFieldSet( - new String[] { line.substring(0, 5), line.substring(6) }, + return line -> new DefaultFieldSet(new String[] { line.substring(0, 5), line.substring(6) }, new String[] { "one", "two" }); } diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfigurationTests.java index c33352e8..b2c500ab 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemWriterAutoConfigurationTests.java @@ -82,17 +82,15 @@ public class FlatFileItemWriterAutoConfigurationTests { properties.setFormatted(true); properties.setDelimited(true); - FlatFileItemWriterAutoConfiguration configuration = new FlatFileItemWriterAutoConfiguration( - properties); + FlatFileItemWriterAutoConfiguration configuration = new FlatFileItemWriterAutoConfiguration(properties); try { configuration.itemWriter(); fail("Exception should have been thrown when both formatted and delimited are selected"); } catch (IllegalStateException ise) { - assertThat(ise.getMessage()).isEqualTo( - "An output file must be either delimited or formatted or a custom " - + "LineAggregator must be provided. Your current configuration specifies both delimited and formatted"); + assertThat(ise.getMessage()).isEqualTo("An output file must be either delimited or formatted or a custom " + + "LineAggregator must be provided. Your current configuration specifies both delimited and formatted"); } catch (Exception e) { fail("Incorrect exception thrown", e); @@ -101,8 +99,7 @@ public class FlatFileItemWriterAutoConfigurationTests { properties.setFormatted(true); properties.setDelimited(false); - ReflectionTestUtils.setField(configuration, "lineAggregator", - new PassThroughLineAggregator<>()); + ReflectionTestUtils.setField(configuration, "lineAggregator", new PassThroughLineAggregator<>()); try { configuration.itemWriter(); @@ -110,8 +107,7 @@ public class FlatFileItemWriterAutoConfigurationTests { } catch (IllegalStateException ise) { assertThat(ise.getMessage()) - .isEqualTo("A LineAggregator must be configured if the " - + "output is not formatted or delimited"); + .isEqualTo("A LineAggregator must be configured if the " + "output is not formatted or delimited"); } catch (Exception e) { fail("Incorrect exception thrown", e); @@ -126,8 +122,7 @@ public class FlatFileItemWriterAutoConfigurationTests { } catch (IllegalStateException ise) { assertThat(ise.getMessage()) - .isEqualTo("A LineAggregator must be configured if the " - + "output is not formatted or delimited"); + .isEqualTo("A LineAggregator must be configured if the " + "output is not formatted or delimited"); } catch (Exception e) { fail("Incorrect exception thrown", e); @@ -138,16 +133,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testDelimitedFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(DelimitedJobConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-16", "spring.batch.job.flatfileitemwriter.saveState=false", @@ -178,15 +169,11 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertFileEquals(new ClassPathResource("writerTestUTF16.txt"), new FileSystemResource(this.outputFile)); - assertThat((Boolean) ReflectionTestUtils.getField(writer, "saveState")) - .isFalse(); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "saveState")).isFalse(); assertThat((Boolean) ReflectionTestUtils.getField(writer, "append")).isTrue(); - assertThat((Boolean) ReflectionTestUtils.getField(writer, "forceSync")) - .isTrue(); - assertThat((Boolean) ReflectionTestUtils.getField(writer, - "shouldDeleteIfExists")).isFalse(); - assertThat((Boolean) ReflectionTestUtils.getField(writer, "transactional")) - .isFalse(); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "forceSync")).isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "shouldDeleteIfExists")).isFalse(); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "transactional")).isFalse(); }); } @@ -194,17 +181,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testFormattedFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(FormattedJobConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=2", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=2", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-8", "spring.batch.job.flatfileitemwriter.formatted=true", @@ -228,8 +210,8 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertLineCount(2, this.outputFile); - String results = FileCopyUtils.copyToString(new InputStreamReader( - new FileSystemResource(this.outputFile).getInputStream())); + String results = FileCopyUtils + .copyToString(new InputStreamReader(new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("item = foo\nitem = bar\n"); }); } @@ -238,17 +220,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testFormattedFieldExtractorFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(FormattedFieldExtractorJobConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-8", "spring.batch.job.flatfileitemwriter.formatted=true", @@ -270,8 +247,8 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertLineCount(3, this.outputFile); - String results = FileCopyUtils.copyToString(new InputStreamReader( - new FileSystemResource(this.outputFile).getInputStream())); + String results = FileCopyUtils + .copyToString(new InputStreamReader(new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("item = f\nitem = b\nitem = b\n"); }); } @@ -280,17 +257,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testFieldExtractorFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(FieldExtractorConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-8", "spring.batch.job.flatfileitemwriter.delimited=true"); @@ -310,8 +282,8 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertLineCount(3, this.outputFile); - String results = FileCopyUtils.copyToString(new InputStreamReader( - new FileSystemResource(this.outputFile).getInputStream())); + String results = FileCopyUtils + .copyToString(new InputStreamReader(new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("f\nb\nb\n"); }); } @@ -320,17 +292,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testCustomLineAggregatorFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(LineAggregatorConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-8"); @@ -349,8 +316,8 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertLineCount(3, this.outputFile); - String results = FileCopyUtils.copyToString(new InputStreamReader( - new FileSystemResource(this.outputFile).getInputStream())); + String results = FileCopyUtils + .copyToString(new InputStreamReader(new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("{item=foo}\n{item=bar}\n{item=baz}\n"); }); } @@ -359,17 +326,12 @@ public class FlatFileItemWriterAutoConfigurationTests { public void testHeaderFooterFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(HeaderFooterConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - FlatFileItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.flatfileitemwriter.name=fooWriter", - String.format( - "spring.batch.job.flatfileitemwriter.resource=file://%s", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + FlatFileItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.flatfileitemwriter.name=fooWriter", + String.format("spring.batch.job.flatfileitemwriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfileitemwriter.encoding=UTF-8", "spring.batch.job.flatfileitemwriter.delimited=true", @@ -390,8 +352,8 @@ public class FlatFileItemWriterAutoConfigurationTests { AssertFile.assertLineCount(5, this.outputFile); - String results = FileCopyUtils.copyToString(new InputStreamReader( - new FileSystemResource(this.outputFile).getInputStream())); + String results = FileCopyUtils + .copyToString(new InputStreamReader(new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("header\nfoo\nbar\nbaz\nfooter"); }); } diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfigurationTests.java index 3ca2ec5d..54bf2b62 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcBatchItemWriterAutoConfigurationTests.java @@ -76,8 +76,8 @@ public class JdbcBatchItemWriterAutoConfigurationTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } @AfterEach @@ -100,43 +100,35 @@ public class JdbcBatchItemWriterAutoConfigurationTests { @Test public void baseTest() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskLauncherConfiguration.class, - JdbcBatchItemWriterAutoConfigurationTests.DelimitedJobConfiguration.class - ) + .withUserConfiguration(TaskLauncherConfiguration.class, + JdbcBatchItemWriterAutoConfigurationTests.DelimitedJobConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcBatchItemWriterAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcBatchItemWriterAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); applicationContextRunner = updatePropertiesForTest(applicationContextRunner); runTest(applicationContextRunner, false); } + @Test public void baseTestWithWriterDataSource() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskLauncherConfiguration.class, - JdbcBatchItemWriterAutoConfigurationTests.DelimitedJobConfiguration.class - ) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcBatchItemWriterAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jdbcbatchitemwriter.datasource.enable=true", - "spring.batch.job.jdbcsinglestep.datasource.enable=false", - "spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbcbatchitemwriter.name=fooWriter", - "spring.batch.job.jdbcbatchitemwriter.sql=INSERT INTO item (item_name) VALUES (:item_name)", - "spring.batch.jdbc.initialize-schema=always", - "jdbcbatchitemwriter.datasource.url=" + DATASOURCE_URL, - "jdbcbatchitemwriter.datasource.username=" + DATASOURCE_USER_NAME, - "jdbcbatchitemwriter.datasource.password=" + DATASOURCE_USER_PASSWORD, - "jdbcbatchitemwriter.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME); + .withUserConfiguration(TaskLauncherConfiguration.class, + JdbcBatchItemWriterAutoConfigurationTests.DelimitedJobConfiguration.class) + .withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcBatchItemWriterAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jdbcbatchitemwriter.datasource.enable=true", + "spring.batch.job.jdbcsinglestep.datasource.enable=false", "spring.batch.job.jobName=job", + "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", + "spring.batch.job.jdbcbatchitemwriter.name=fooWriter", + "spring.batch.job.jdbcbatchitemwriter.sql=INSERT INTO item (item_name) VALUES (:item_name)", + "spring.batch.jdbc.initialize-schema=always", + "jdbcbatchitemwriter.datasource.url=" + DATASOURCE_URL, + "jdbcbatchitemwriter.datasource.username=" + DATASOURCE_USER_NAME, + "jdbcbatchitemwriter.datasource.password=" + DATASOURCE_USER_PASSWORD, + "jdbcbatchitemwriter.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME); runTest(applicationContextRunner, true); } @@ -144,16 +136,13 @@ public class JdbcBatchItemWriterAutoConfigurationTests { @Test public void customSqlParameterSourceTest() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskLauncherConfiguration.class, + .withUserConfiguration(TaskLauncherConfiguration.class, JdbcBatchItemWriterAutoConfigurationTests.DelimitedDifferentKeyNameJobConfiguration.class, CustomSqlParameterSourceProviderConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcBatchItemWriterAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcBatchItemWriterAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); applicationContextRunner = updatePropertiesForTest(applicationContextRunner); runTest(applicationContextRunner, false); @@ -162,22 +151,18 @@ public class JdbcBatchItemWriterAutoConfigurationTests { @Test public void preparedStatementSetterTest() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskLauncherConfiguration.class, + .withUserConfiguration(TaskLauncherConfiguration.class, JdbcBatchItemWriterAutoConfigurationTests.DelimitedJobConfiguration.class, ItemPreparedStatementSetterConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcBatchItemWriterAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcBatchItemWriterAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jdbcsinglestep.datasource.enable=false"); applicationContextRunner = updatePropertiesForTest(applicationContextRunner); runTest(applicationContextRunner, false); } - private ApplicationContextRunner updatePropertiesForTest( - ApplicationContextRunner applicationContextRunner) { + private ApplicationContextRunner updatePropertiesForTest(ApplicationContextRunner applicationContextRunner) { return applicationContextRunner.withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", "spring.batch.job.jdbcbatchitemwriter.name=fooWriter", @@ -194,8 +179,7 @@ public class JdbcBatchItemWriterAutoConfigurationTests { dataSource = context.getBean("jdbcBatchItemWriterSpringDataSource", DataSource.class); } JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - List> result = jdbcTemplate - .queryForList("SELECT item_name FROM item ORDER BY item_name"); + List> result = jdbcTemplate.queryForList("SELECT item_name FROM item ORDER BY item_name"); assertThat(result.size()).isEqualTo(3); assertThat(result.get(0).get("item_name")).isEqualTo("bar"); @@ -203,16 +187,13 @@ public class JdbcBatchItemWriterAutoConfigurationTests { assertThat(result.get(2).get("item_name")).isEqualTo("foo"); JdbcBatchItemWriter writer = context.getBean(JdbcBatchItemWriter.class); - assertThat((Boolean) ReflectionTestUtils.getField(writer, "assertUpdates")) - .isTrue(); - assertThat((Integer) ReflectionTestUtils.getField(writer, "parameterCount")) - .isEqualTo(1); - assertThat((Boolean) ReflectionTestUtils.getField(writer, "usingNamedParameters")) - .isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "assertUpdates")).isTrue(); + assertThat((Integer) ReflectionTestUtils.getField(writer, "parameterCount")).isEqualTo(1); + assertThat((Boolean) ReflectionTestUtils.getField(writer, "usingNamedParameters")).isTrue(); if (!isWriterDataSourcePresent) { - assertThatThrownBy(() -> context.getBean("jdbcBatchItemWriterSpringDataSource")) - .isInstanceOf(NoSuchBeanDefinitionException.class) - .hasMessageContaining("No bean named 'jdbcBatchItemWriterSpringDataSource' available"); + assertThatThrownBy(() -> context.getBean("jdbcBatchItemWriterSpringDataSource")) + .isInstanceOf(NoSuchBeanDefinitionException.class) + .hasMessageContaining("No bean named 'jdbcBatchItemWriterSpringDataSource' available"); } else { assertThat(context.getBean("jdbcBatchItemWriterSpringDataSource")).isNotNull(); @@ -247,19 +228,16 @@ public class JdbcBatchItemWriterAutoConfigurationTests { Server server = null; try { if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); defaultServer = server; DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(DATASOURCE_DRIVER_CLASS_NAME); dataSource.setUrl(DATASOURCE_URL); dataSource.setUsername(DATASOURCE_USER_NAME); dataSource.setPassword(DATASOURCE_USER_PASSWORD); - ClassPathResource setupResource = new ClassPathResource( - "schema-h2.sql"); - ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator( - setupResource); + ClassPathResource setupResource = new ClassPathResource("schema-h2.sql"); + ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(setupResource); resourceDatabasePopulator.execute(dataSource); } } @@ -340,11 +318,9 @@ public class JdbcBatchItemWriterAutoConfigurationTests { public ItemPreparedStatementSetter itemPreparedStatementSetter() { return new ItemPreparedStatementSetter() { @Override - public void setValues(Object item, PreparedStatement ps) - throws SQLException { + public void setValues(Object item, PreparedStatement ps) throws SQLException { Map mapItem = (Map) item; - StatementCreatorUtils.setParameterValue(ps, 1, - SqlTypeValue.TYPE_UNKNOWN, mapItem.get("item_name")); + StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, mapItem.get("item_name")); } }; } diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfigurationTests.java index 580e6bfd..19977cc5 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/jdbc/JdbcCursorItemReaderAutoConfigurationTests.java @@ -74,8 +74,8 @@ public class JdbcCursorItemReaderAutoConfigurationTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } @AfterAll @@ -93,13 +93,12 @@ public class JdbcCursorItemReaderAutoConfigurationTests { @Test public void testIntegration() { - ApplicationContextRunner applicationContextRunner = applicationContextRunner() - .withPropertyValues("spring.batch.job.jobName=integrationJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbccursoritemreader.name=fooReader", - "spring.batch.job.jdbccursoritemreader.sql=select item_name from item", - "spring.batch.jdbc.initialize-schema=always", - "spring.batch.job.jdbcsinglestep.datasource.enable=false"); + ApplicationContextRunner applicationContextRunner = applicationContextRunner().withPropertyValues( + "spring.batch.job.jobName=integrationJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.jdbccursoritemreader.name=fooReader", + "spring.batch.job.jdbccursoritemreader.sql=select item_name from item", + "spring.batch.jdbc.initialize-schema=always", + "spring.batch.job.jdbcsinglestep.datasource.enable=false"); applicationContextRunner.run((context) -> { JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -114,38 +113,32 @@ public class JdbcCursorItemReaderAutoConfigurationTests { Thread.sleep(1000); } - List> items = context.getBean(ListItemWriter.class) - .getWrittenItems(); + List> items = context.getBean(ListItemWriter.class).getWrittenItems(); assertThat(items.size()).isEqualTo(3); assertThat(items.get(0).get("ITEM_NAME")).isEqualTo("foo"); assertThat(items.get(1).get("ITEM_NAME")).isEqualTo("bar"); assertThat(items.get(2).get("ITEM_NAME")).isEqualTo("baz"); assertThatThrownBy(() -> context.getBean("readerSpringDataSource")) - .isInstanceOf(NoSuchBeanDefinitionException.class) - .hasMessageContaining("No bean named 'readerSpringDataSource' available"); + .isInstanceOf(NoSuchBeanDefinitionException.class) + .hasMessageContaining("No bean named 'readerSpringDataSource' available"); }); } private ApplicationContextRunner applicationContextRunner() { return new ApplicationContextRunner() - .withUserConfiguration(TaskLauncherConfiguration.class, BaseConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcCursorItemReaderAutoConfiguration.class)); + .withUserConfiguration(TaskLauncherConfiguration.class, BaseConfiguration.class).withConfiguration( + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcCursorItemReaderAutoConfiguration.class)); } @Test public void testIntegrationReaderDataSourceEnabled() { - ApplicationContextRunner applicationContextRunner = applicationContextRunner() - .withPropertyValues("spring.batch.job.jobName=integrationReaderJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbccursoritemreader.name=fooReader", + ApplicationContextRunner applicationContextRunner = applicationContextRunner().withPropertyValues( + "spring.batch.job.jobName=integrationReaderJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.jdbccursoritemreader.name=fooReader", "spring.batch.job.jdbccursoritemreader.sql=select item_name from item", - "spring.batch.jdbc.initialize-schema=always", - "spring.batch.job.jdbcsinglestep.datasource.enable=false", + "spring.batch.jdbc.initialize-schema=always", "spring.batch.job.jdbcsinglestep.datasource.enable=false", "spring.batch.job.jdbccursoritemreader.datasource.enable=true", "jdbccursoritemreader.datasource.url=" + DATASOURCE_URL, "jdbccursoritemreader.datasource.username=" + DATASOURCE_USER_NAME, @@ -165,8 +158,7 @@ public class JdbcCursorItemReaderAutoConfigurationTests { Thread.sleep(1000); } - List> items = context.getBean(ListItemWriter.class) - .getWrittenItems(); + List> items = context.getBean(ListItemWriter.class).getWrittenItems(); assertThat(items.size()).isEqualTo(3); assertThat(items.get(0).get("ITEM_NAME")).isEqualTo("foo"); @@ -181,13 +173,10 @@ public class JdbcCursorItemReaderAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(TaskLauncherConfiguration.class, RowMapperConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcCursorItemReaderAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=rowMapperJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbccursoritemreader.name=fooReader", + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcCursorItemReaderAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=rowMapperJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.jdbccursoritemreader.name=fooReader", "spring.batch.job.jdbccursoritemreader.sql=select * from item", "spring.batch.jdbc.initialize-schema=always", "spring.batch.job.jdbcsinglestep.datasource.enable=false"); @@ -205,8 +194,7 @@ public class JdbcCursorItemReaderAutoConfigurationTests { Thread.sleep(1000); } - List> items = context.getBean(ListItemWriter.class) - .getWrittenItems(); + List> items = context.getBean(ListItemWriter.class).getWrittenItems(); assertThat(items.size()).isEqualTo(3); assertThat(items.get(0).get("item")).isEqualTo("foo"); @@ -220,13 +208,10 @@ public class JdbcCursorItemReaderAutoConfigurationTests { final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(TaskLauncherConfiguration.class, BaseConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcCursorItemReaderAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=roseyJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbccursoritemreader.saveState=false", + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcCursorItemReaderAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=roseyJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.jdbccursoritemreader.saveState=false", "spring.batch.job.jdbccursoritemreader.name=fooReader", "spring.batch.job.jdbccursoritemreader.maxItemCount=15", "spring.batch.job.jdbccursoritemreader.currentItemCount=2", @@ -241,8 +226,7 @@ public class JdbcCursorItemReaderAutoConfigurationTests { applicationContextRunner.run((context) -> { - JdbcCursorItemReader> itemReader = context - .getBean(JdbcCursorItemReader.class); + JdbcCursorItemReader> itemReader = context.getBean(JdbcCursorItemReader.class); validateBean(itemReader); }); @@ -251,31 +235,19 @@ public class JdbcCursorItemReaderAutoConfigurationTests { private void validateBean(JdbcCursorItemReader itemReader) { assertThat(itemReader.getSql()).isEqualTo("select * from foo"); assertThat(itemReader.getDataSource()).isNotNull(); - assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "saveState")) - .isFalse(); - assertThat( - ReflectionTestUtils.getField( - (ExecutionContextUserSupport) ReflectionTestUtils - .getField(itemReader, "executionContextUserSupport"), - "name")).isEqualTo("fooReader"); - assertThat((Integer) ReflectionTestUtils.getField(itemReader, "maxItemCount")) - .isEqualTo(15); - assertThat((Integer) ReflectionTestUtils.getField(itemReader, "currentItemCount")) - .isEqualTo(2); - assertThat((Integer) ReflectionTestUtils.getField(itemReader, "fetchSize")) - .isEqualTo(4); - assertThat((Integer) ReflectionTestUtils.getField(itemReader, "maxRows")) - .isEqualTo(6); - assertThat((Integer) ReflectionTestUtils.getField(itemReader, "queryTimeout")) - .isEqualTo(8); - assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "ignoreWarnings")) - .isTrue(); - assertThat((Boolean) ReflectionTestUtils.getField(itemReader, - "verifyCursorPosition")).isTrue(); - assertThat((Boolean) ReflectionTestUtils.getField(itemReader, - "driverSupportsAbsolute")).isTrue(); - assertThat((Boolean) ReflectionTestUtils.getField(itemReader, - "useSharedExtendedConnection")).isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "saveState")).isFalse(); + assertThat(ReflectionTestUtils.getField( + (ExecutionContextUserSupport) ReflectionTestUtils.getField(itemReader, "executionContextUserSupport"), + "name")).isEqualTo("fooReader"); + assertThat((Integer) ReflectionTestUtils.getField(itemReader, "maxItemCount")).isEqualTo(15); + assertThat((Integer) ReflectionTestUtils.getField(itemReader, "currentItemCount")).isEqualTo(2); + assertThat((Integer) ReflectionTestUtils.getField(itemReader, "fetchSize")).isEqualTo(4); + assertThat((Integer) ReflectionTestUtils.getField(itemReader, "maxRows")).isEqualTo(6); + assertThat((Integer) ReflectionTestUtils.getField(itemReader, "queryTimeout")).isEqualTo(8); + assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "ignoreWarnings")).isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "verifyCursorPosition")).isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "driverSupportsAbsolute")).isTrue(); + assertThat((Boolean) ReflectionTestUtils.getField(itemReader, "useSharedExtendedConnection")).isTrue(); } @Test @@ -283,18 +255,14 @@ public class JdbcCursorItemReaderAutoConfigurationTests { final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(TaskLauncherConfiguration.class, BaseConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcCursorItemReaderAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=noNameJob", - "spring.batch.job.stepName=step1", + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcCursorItemReaderAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=noNameJob", "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5"); assertThatThrownBy(() -> { runTest(applicationContextRunner); - }).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("UnsatisfiedDependencyException"); + }).isInstanceOf(IllegalStateException.class).hasMessageContaining("UnsatisfiedDependencyException"); } @Test @@ -302,18 +270,14 @@ public class JdbcCursorItemReaderAutoConfigurationTests { final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(TaskLauncherConfiguration.class, BaseConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - JdbcCursorItemReaderAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.jdbccursoritemreader.name=fooReader"); + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, JdbcCursorItemReaderAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.jdbccursoritemreader.name=fooReader"); assertThatThrownBy(() -> { runTest(applicationContextRunner); - }).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("UnsatisfiedDependencyException"); + }).isInstanceOf(IllegalStateException.class).hasMessageContaining("UnsatisfiedDependencyException"); } private void runTest(ApplicationContextRunner applicationContextRunner) { @@ -332,7 +296,8 @@ public class JdbcCursorItemReaderAutoConfigurationTests { }); } - @AutoConfigureBefore({JdbcCursorItemReaderAutoConfiguration.class, JDBCSingleStepDataSourceAutoConfiguration.class}) + @AutoConfigureBefore({ JdbcCursorItemReaderAutoConfiguration.class, + JDBCSingleStepDataSourceAutoConfiguration.class }) @Configuration public static class TaskLauncherConfiguration { @@ -343,19 +308,16 @@ public class JdbcCursorItemReaderAutoConfigurationTests { Server server = null; try { if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); defaultServer = server; DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(DATASOURCE_DRIVER_CLASS_NAME); dataSource.setUrl(DATASOURCE_URL); dataSource.setUsername(DATASOURCE_USER_NAME); dataSource.setPassword(DATASOURCE_USER_PASSWORD); - ClassPathResource setupResource = new ClassPathResource( - "schema-h2.sql"); - ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator( - setupResource); + ClassPathResource setupResource = new ClassPathResource("schema-h2.sql"); + ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(setupResource); resourceDatabasePopulator.setContinueOnError(true); resourceDatabasePopulator.execute(dataSource); diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfigurationTests.java index 88ab4733..bbc7c81c 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemReaderAutoConfigurationTests.java @@ -61,8 +61,7 @@ public class KafkaItemReaderAutoConfigurationTests { @BeforeAll public static void setupTest(EmbeddedKafkaBroker embeddedKafka) { embeddedKafkaBroker = embeddedKafka; - embeddedKafka.addTopics(new NewTopic("topic1", 1, (short) 1), - new NewTopic("topic2", 2, (short) 1), + embeddedKafka.addTopics(new NewTopic("topic1", 1, (short) 1), new NewTopic("topic2", 2, (short) 1), new NewTopic("topic3", 1, (short) 1)); } @@ -72,22 +71,16 @@ public class KafkaItemReaderAutoConfigurationTests { populateSingleTopic(topicName); ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomMappingConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - KafkaItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.kafka.consumer.bootstrap-servers=" - + embeddedKafkaBroker.getBrokersAsString(), - "spring.kafka.consumer.group-id=1", - "spring.batch.job.kafkaitemreader.name=kafkaItemReader", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + KafkaItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", + "spring.kafka.consumer.bootstrap-servers=" + embeddedKafkaBroker.getBrokersAsString(), + "spring.kafka.consumer.group-id=1", "spring.batch.job.kafkaitemreader.name=kafkaItemReader", "spring.batch.job.kafkaitemreader.poll-time-out-in-seconds=2", "spring.batch.job.kafkaitemreader.topic=" + topicName, - "spring.kafka.consumer.value-deserializer=" - + JsonDeserializer.class.getName()); + "spring.kafka.consumer.value-deserializer=" + JsonDeserializer.class.getName()); applicationContextRunner.run((context) -> { JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -120,23 +113,17 @@ public class KafkaItemReaderAutoConfigurationTests { populateSingleTopic(topicName); ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomMappingConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - KafkaItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.kafka.consumer.bootstrap-servers=" - + embeddedKafkaBroker.getBrokersAsString(), - "spring.kafka.consumer.group-id=1", - "spring.batch.job.kafkaitemreader.name=kafkaItemReader", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + KafkaItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", + "spring.kafka.consumer.bootstrap-servers=" + embeddedKafkaBroker.getBrokersAsString(), + "spring.kafka.consumer.group-id=1", "spring.batch.job.kafkaitemreader.name=kafkaItemReader", "spring.batch.job.kafkaitemreader.partitions=0,1", "spring.batch.job.kafkaitemreader.poll-time-out-in-seconds=2", "spring.batch.job.kafkaitemreader.topic=" + topicName, - "spring.kafka.consumer.value-deserializer=" - + JsonDeserializer.class.getName()); + "spring.kafka.consumer.value-deserializer=" + JsonDeserializer.class.getName()); applicationContextRunner.run((context) -> { JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -163,21 +150,15 @@ public class KafkaItemReaderAutoConfigurationTests { populateSingleTopic(topicName); ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomMappingConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - KafkaItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.kafka.consumer.bootstrap-servers=" - + embeddedKafkaBroker.getBrokersAsString(), - "spring.kafka.consumer.group-id=1", - "spring.batch.job.kafkaitemreader.name=kafkaItemReader", + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + KafkaItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", + "spring.kafka.consumer.bootstrap-servers=" + embeddedKafkaBroker.getBrokersAsString(), + "spring.kafka.consumer.group-id=1", "spring.batch.job.kafkaitemreader.name=kafkaItemReader", "spring.batch.job.kafkaitemreader.topic=" + topicName, - "spring.kafka.consumer.value-deserializer=" - + JsonDeserializer.class.getName()); + "spring.kafka.consumer.value-deserializer=" + JsonDeserializer.class.getName()); Date startTime = new Date(); applicationContextRunner.run((context) -> { JobLauncher jobLauncher = context.getBean(JobLauncher.class); @@ -212,10 +193,9 @@ public class KafkaItemReaderAutoConfigurationTests { } private void populateSingleTopic(String topic) { - Map configps = new HashMap<>( - KafkaTestUtils.producerProps(embeddedKafkaBroker)); - Producer producer = new DefaultKafkaProducerFactory<>(configps, - new StringSerializer(), new JsonSerializer<>()).createProducer(); + Map configps = new HashMap<>(KafkaTestUtils.producerProps(embeddedKafkaBroker)); + Producer producer = new DefaultKafkaProducerFactory<>(configps, new StringSerializer(), + new JsonSerializer<>()).createProducer(); Map testMap = new HashMap<>(); testMap.put("first_name", "jane"); producer.send(new ProducerRecord<>(topic, "my-aggregate-id", testMap)); @@ -235,10 +215,12 @@ public class KafkaItemReaderAutoConfigurationTests { @EnableBatchProcessing @Configuration public static class CustomMappingConfiguration { + @Bean public ListItemWriter> itemWriter() { return new ListItemWriter<>(); } + } } diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterTests.java index 5fb599b4..34795e3a 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/kafka/KafkaItemWriterTests.java @@ -68,16 +68,12 @@ public class KafkaItemWriterTests { final String topicName = "topic1"; ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(CustomMappingConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - KafkaItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=job", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.kafka.producer.bootstrap-servers=" - + embeddedKafkaBroker.getBrokersAsString(), + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + KafkaItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", + "spring.kafka.producer.bootstrap-servers=" + embeddedKafkaBroker.getBrokersAsString(), "spring.kafka.producer.keySerializer=org.springframework.kafka.support.serializer.JsonSerializer", "spring.batch.job.kafkaitemwriter.topic=" + topicName); @@ -88,14 +84,12 @@ public class KafkaItemWriterTests { } private void validateResults(String topicName) { - Map configs = new HashMap<>( - KafkaTestUtils.consumerProps("1", "false", embeddedKafkaBroker)); - Consumer consumer = new DefaultKafkaConsumerFactory<>(configs, - new StringDeserializer(), new JsonDeserializer<>()).createConsumer(); + Map configs = new HashMap<>(KafkaTestUtils.consumerProps("1", "false", embeddedKafkaBroker)); + Consumer consumer = new DefaultKafkaConsumerFactory<>(configs, new StringDeserializer(), + new JsonDeserializer<>()).createConsumer(); consumer.subscribe(singleton(topicName)); - ConsumerRecords consumerRecords = KafkaTestUtils - .getRecords(consumer); + ConsumerRecords consumerRecords = KafkaTestUtils.getRecords(consumer); assertThat(consumerRecords.count()).isEqualTo(5); List> result = new ArrayList<>(); consumerRecords.forEach(cs -> { @@ -137,8 +131,7 @@ public class KafkaItemWriterTests { return new ListItemReader<>(list); } - private void addNameToReaderList(List> itemReaderList, - String value) { + private void addNameToReaderList(List> itemReaderList, String value) { Map prepMap = new HashMap<>(); prepMap.put("first_name", value); itemReaderList.add(prepMap); diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfigurationTests.java index 7e18368a..e886b4df 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemReaderAutoConfigurationTests.java @@ -68,8 +68,7 @@ public class AmqpItemReaderAutoConfigurationTests { private ConnectionFactory connectionFactory; static { - GenericContainer rabbitmq = new RabbitMQContainer("rabbitmq:3.8.9") - .withExposedPorts(5672); + GenericContainer rabbitmq = new RabbitMQContainer("rabbitmq:3.8.9").withExposedPorts(5672); rabbitmq.start(); final Integer mappedPort = rabbitmq.getMappedPort(5672); host = rabbitmq.getHost(); @@ -107,17 +106,12 @@ public class AmqpItemReaderAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(BaseConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - AmqpItemReaderAutoConfiguration.class, - RabbitAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=integrationJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.amqpitemreader.enabled=true", - "spring.rabbitmq.template.default-receive-queue=foo", - "spring.rabbitmq.host=" + host, + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, AmqpItemReaderAutoConfiguration.class, + RabbitAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=integrationJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.amqpitemreader.enabled=true", + "spring.rabbitmq.template.default-receive-queue=foo", "spring.rabbitmq.host=" + host, "spring.rabbitmq.port=" + amqpPort); applicationContextRunner.run((context) -> { @@ -138,17 +132,12 @@ public class AmqpItemReaderAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(ItemTypeConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - AmqpItemReaderAutoConfiguration.class, - RabbitAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=integrationJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.amqpitemreader.enabled=true", - "spring.rabbitmq.template.default-receive-queue=foo", - "spring.rabbitmq.host=" + host, + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, AmqpItemReaderAutoConfiguration.class, + RabbitAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=integrationJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.amqpitemreader.enabled=true", + "spring.rabbitmq.template.default-receive-queue=foo", "spring.rabbitmq.host=" + host, "spring.rabbitmq.port=" + amqpPort); applicationContextRunner.run((context) -> { @@ -167,17 +156,12 @@ public class AmqpItemReaderAutoConfigurationTests { void useAmqpTemplateTest() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(MockTemplateConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - AmqpItemReaderAutoConfiguration.class, - DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.batch.job.jobName=integrationJob", - "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.batch.job.amqpitemreader.enabled=true", - "spring.rabbitmq.host=" + host, - "spring.rabbitmq.port=" + amqpPort); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + AmqpItemReaderAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.batch.job.jobName=integrationJob", "spring.batch.job.stepName=step1", + "spring.batch.job.chunkSize=5", "spring.batch.job.amqpitemreader.enabled=true", + "spring.rabbitmq.host=" + host, "spring.rabbitmq.port=" + amqpPort); applicationContextRunner.run((context) -> { runJob(context); diff --git a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfigurationTests.java b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfigurationTests.java index c0835732..e1b36825 100644 --- a/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfigurationTests.java +++ b/spring-cloud-starter-single-step-batch-job/src/test/java/org/springframework/cloud/task/batch/autoconfigure/rabbit/AmqpItemWriterAutoConfigurationTests.java @@ -81,8 +81,7 @@ public class AmqpItemWriterAutoConfigurationTests { private String[] configurations; static { - GenericContainer rabbitmq = new RabbitMQContainer("rabbitmq:3.8.9") - .withExposedPorts(5672); + GenericContainer rabbitmq = new RabbitMQContainer("rabbitmq:3.8.9").withExposedPorts(5672); rabbitmq.start(); final Integer mappedPort = rabbitmq.getMappedPort(5672); host = rabbitmq.getHost(); @@ -95,8 +94,7 @@ public class AmqpItemWriterAutoConfigurationTests { addNameToReaderList(sampleData, "Judy"); } - private static void addNameToReaderList(List> itemReaderList, - String value) { + private static void addNameToReaderList(List> itemReaderList, String value) { Map prepMap = new HashMap<>(); prepMap.put("first_name", value); itemReaderList.add(prepMap); @@ -110,14 +108,11 @@ public class AmqpItemWriterAutoConfigurationTests { AmqpAdmin admin = new RabbitAdmin(this.connectionFactory); admin.declareQueue(new Queue(QUEUE_NAME)); admin.declareExchange(new TopicExchange(EXCHANGE_NAME)); - admin.declareBinding(new Binding(QUEUE_NAME, Binding.DestinationType.QUEUE, - EXCHANGE_NAME, "#", null)); + admin.declareBinding(new Binding(QUEUE_NAME, Binding.DestinationType.QUEUE, EXCHANGE_NAME, "#", null)); this.configurations = new String[] { "spring.batch.job.jobName=integrationJob", "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", - "spring.rabbitmq.template.exchange=" + EXCHANGE_NAME, - "spring.rabbitmq.host=" + host, - "spring.batch.job.amqpitemwriter.enabled=true", - "spring.rabbitmq.port=" + amqpPort }; + "spring.rabbitmq.template.exchange=" + EXCHANGE_NAME, "spring.rabbitmq.host=" + host, + "spring.batch.job.amqpitemwriter.enabled=true", "spring.rabbitmq.port=" + amqpPort }; } @AfterEach @@ -132,12 +127,9 @@ public class AmqpItemWriterAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(BaseConfiguration.class) .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - AmqpItemWriterAutoConfiguration.class, - RabbitAutoConfiguration.class, - DataSourceAutoConfiguration.class)) + AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + SingleStepJobAutoConfiguration.class, AmqpItemWriterAutoConfiguration.class, + RabbitAutoConfiguration.class, DataSourceAutoConfiguration.class)) .withPropertyValues(this.configurations); applicationContextRunner.run((context) -> { @@ -149,10 +141,8 @@ public class AmqpItemWriterAutoConfigurationTests { } for (Map sampleEntry : sampleData) { - Map map = (Map) template - .receiveAndConvert(QUEUE_NAME); - assertThat(map.get("first_name")) - .isEqualTo(sampleEntry.get("first_name")); + Map map = (Map) template.receiveAndConvert(QUEUE_NAME); + assertThat(map.get("first_name")).isEqualTo(sampleEntry.get("first_name")); } }); } @@ -161,12 +151,9 @@ public class AmqpItemWriterAutoConfigurationTests { void useAmqpTemplateTest() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(MockConfiguration.class) - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, - SingleStepJobAutoConfiguration.class, - AmqpItemWriterAutoConfiguration.class, - DataSourceAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, + AmqpItemWriterAutoConfiguration.class, DataSourceAutoConfiguration.class)) .withPropertyValues(this.configurations); applicationContextRunner.run((context) -> { diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/JobLaunchCondition.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/JobLaunchCondition.java index 971ad898..88716676 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/JobLaunchCondition.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/JobLaunchCondition.java @@ -31,14 +31,12 @@ public class JobLaunchCondition extends AllNestedConditions { super(ConfigurationPhase.PARSE_CONFIGURATION); } - @ConditionalOnProperty(name = "spring.cloud.task.batch.fail-on-job-failure", - havingValue = "true") + @ConditionalOnProperty(name = "spring.cloud.task.batch.fail-on-job-failure", havingValue = "true") static class FailOnJobFailureCondition { } - @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true) static class SpringBatchJobCondition { } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchAutoConfiguration.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchAutoConfiguration.java index a2a83ecb..19eb03a1 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchAutoConfiguration.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchAutoConfiguration.java @@ -40,10 +40,8 @@ import org.springframework.context.annotation.Configuration; * @author Michael Minella */ @Configuration(proxyBeanMethods = false) -@ConditionalOnBean({Job.class, TaskLifecycleListener.class}) -@ConditionalOnProperty( - name = { "spring.cloud.task.batch.listener.enable", - "spring.cloud.task.batch.listener.enabled" }, +@ConditionalOnBean({ Job.class, TaskLifecycleListener.class }) +@ConditionalOnProperty(name = { "spring.cloud.task.batch.listener.enable", "spring.cloud.task.batch.listener.enabled" }, havingValue = "true", matchIfMissing = true) public class TaskBatchAutoConfiguration { @@ -68,15 +66,13 @@ public class TaskBatchAutoConfiguration { private TaskProperties taskProperties; @Bean - public TaskBatchExecutionListenerFactoryBean taskBatchExecutionListener( - TaskExplorer taskExplorer) { + public TaskBatchExecutionListenerFactoryBean taskBatchExecutionListener(TaskExplorer taskExplorer) { TaskConfigurer taskConfigurer = null; if (!this.context.getBeansOfType(TaskConfigurer.class).isEmpty()) { taskConfigurer = this.context.getBean(TaskConfigurer.class); } if (taskConfigurer != null && taskConfigurer.getTaskDataSource() != null) { - return new TaskBatchExecutionListenerFactoryBean( - taskConfigurer.getTaskDataSource(), taskExplorer, + return new TaskBatchExecutionListenerFactoryBean(taskConfigurer.getTaskDataSource(), taskExplorer, this.taskProperties.getTablePrefix()); } else { diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerBeanPostProcessor.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerBeanPostProcessor.java index 7b7801e0..b5700749 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerBeanPostProcessor.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerBeanPostProcessor.java @@ -43,28 +43,24 @@ public class TaskBatchExecutionListenerBeanPostProcessor implements BeanPostProc private List jobNames = new ArrayList<>(); @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (this.jobNames.size() > 0 && !this.jobNames.contains(beanName)) { return bean; } - int length = this.applicationContext - .getBeanNamesForType(TaskBatchExecutionListener.class).length; + int length = this.applicationContext.getBeanNamesForType(TaskBatchExecutionListener.class).length; if (bean instanceof AbstractJob) { if (length != 1) { throw new IllegalStateException("The application context is required to " - + "have exactly 1 instance of the TaskBatchExecutionListener but has " - + length); + + "have exactly 1 instance of the TaskBatchExecutionListener but has " + length); } - ((AbstractJob) bean).registerJobExecutionListener( - this.applicationContext.getBean(TaskBatchExecutionListener.class)); + ((AbstractJob) bean) + .registerJobExecutionListener(this.applicationContext.getBean(TaskBatchExecutionListener.class)); } return bean; } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerFactoryBean.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerFactoryBean.java index fe759987..fcf2eff6 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerFactoryBean.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskBatchExecutionListenerFactoryBean.java @@ -40,8 +40,7 @@ import org.springframework.util.ReflectionUtils; * * @author Michael Minella */ -public class TaskBatchExecutionListenerFactoryBean - implements FactoryBean { +public class TaskBatchExecutionListenerFactoryBean implements FactoryBean { private TaskBatchExecutionListener listener; @@ -57,8 +56,7 @@ public class TaskBatchExecutionListenerFactoryBean * @param dataSource the dataSource to use for the TaskBatchExecutionListener. * @param taskExplorer the taskExplorer to use for the TaskBatchExecutionListener. */ - public TaskBatchExecutionListenerFactoryBean(DataSource dataSource, - TaskExplorer taskExplorer) { + public TaskBatchExecutionListenerFactoryBean(DataSource dataSource, TaskExplorer taskExplorer) { this.dataSource = dataSource; this.taskExplorer = taskExplorer; } @@ -70,8 +68,7 @@ public class TaskBatchExecutionListenerFactoryBean * @param tablePrefix the prefix for the task tables accessed by the * TaskBatchExecutionListener. */ - public TaskBatchExecutionListenerFactoryBean(DataSource dataSource, - TaskExplorer taskExplorer, String tablePrefix) { + public TaskBatchExecutionListenerFactoryBean(DataSource dataSource, TaskExplorer taskExplorer, String tablePrefix) { this(dataSource, taskExplorer); Assert.hasText(tablePrefix, "tablePrefix must not be null nor empty."); this.tablePrefix = tablePrefix; @@ -86,8 +83,7 @@ public class TaskBatchExecutionListenerFactoryBean this.listener = new TaskBatchExecutionListener(getMapTaskBatchDao()); } else { - this.listener = new TaskBatchExecutionListener( - new JdbcTaskBatchDao(this.dataSource, this.tablePrefix)); + this.listener = new TaskBatchExecutionListener(new JdbcTaskBatchDao(this.dataSource, this.tablePrefix)); } return this.listener; @@ -104,8 +100,7 @@ public class TaskBatchExecutionListenerFactoryBean } private MapTaskBatchDao getMapTaskBatchDao() throws Exception { - Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class, - "taskExecutionDao"); + Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class, "taskExecutionDao"); taskExecutionDaoField.setAccessible(true); MapTaskExecutionDao taskExecutionDao; @@ -114,12 +109,11 @@ public class TaskBatchExecutionListenerFactoryBean SimpleTaskExplorer dereferencedTaskRepository = (SimpleTaskExplorer) ((Advised) this.taskExplorer) .getTargetSource().getTarget(); - taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils - .getField(taskExecutionDaoField, dereferencedTaskRepository); + taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils.getField(taskExecutionDaoField, + dereferencedTaskRepository); } else { - taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils - .getField(taskExecutionDaoField, this.taskExplorer); + taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils.getField(taskExecutionDaoField, this.taskExplorer); } return new MapTaskBatchDao(taskExecutionDao.getBatchJobAssociations()); diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherApplicationRunnerFactoryBean.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherApplicationRunnerFactoryBean.java index d9bbaea1..e80ee874 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherApplicationRunnerFactoryBean.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherApplicationRunnerFactoryBean.java @@ -35,8 +35,7 @@ import org.springframework.util.StringUtils; * @author Glenn Renfro * @since 2.3.0 */ -public class TaskJobLauncherApplicationRunnerFactoryBean - implements FactoryBean { +public class TaskJobLauncherApplicationRunnerFactoryBean implements FactoryBean { private JobLauncher jobLauncher; @@ -54,10 +53,9 @@ public class TaskJobLauncherApplicationRunnerFactoryBean private JobRepository jobRepository; - public TaskJobLauncherApplicationRunnerFactoryBean(JobLauncher jobLauncher, - JobExplorer jobExplorer, List jobs, - TaskBatchProperties taskBatchProperties, JobRegistry jobRegistry, - JobRepository jobRepository, BatchProperties batchProperties) { + public TaskJobLauncherApplicationRunnerFactoryBean(JobLauncher jobLauncher, JobExplorer jobExplorer, List 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"); Assert.notEmpty(jobs, "jobs must not be null nor empty"); @@ -85,8 +83,7 @@ public class TaskJobLauncherApplicationRunnerFactoryBean @Override public TaskJobLauncherApplicationRunner getObject() { TaskJobLauncherApplicationRunner taskJobLauncherApplicationRunner = new TaskJobLauncherApplicationRunner( - this.jobLauncher, this.jobExplorer, this.jobRepository, - this.taskBatchProperties); + this.jobLauncher, this.jobExplorer, this.jobRepository, this.taskBatchProperties); taskJobLauncherApplicationRunner.setJobs(this.jobs); if (StringUtils.hasText(this.jobName)) { taskJobLauncherApplicationRunner.setJobName(this.jobName); diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfiguration.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfiguration.java index 5bca6c93..14185138 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfiguration.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfiguration.java @@ -49,16 +49,13 @@ public class TaskJobLauncherAutoConfiguration { private TaskBatchProperties properties; @Bean - @ConditionalOnClass( - name = "org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner") - public TaskJobLauncherApplicationRunnerFactoryBean taskJobLauncherApplicationRunner( - JobLauncher jobLauncher, JobExplorer jobExplorer, List jobs, - JobRegistry jobRegistry, JobRepository jobRepository, + @ConditionalOnClass(name = "org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner") + public TaskJobLauncherApplicationRunnerFactoryBean taskJobLauncherApplicationRunner(JobLauncher jobLauncher, + JobExplorer jobExplorer, List jobs, JobRegistry jobRegistry, JobRepository jobRepository, BatchProperties batchProperties) { TaskJobLauncherApplicationRunnerFactoryBean taskJobLauncherApplicationRunnerFactoryBean; - taskJobLauncherApplicationRunnerFactoryBean = new TaskJobLauncherApplicationRunnerFactoryBean( - jobLauncher, jobExplorer, jobs, this.properties, jobRegistry, - jobRepository, batchProperties); + taskJobLauncherApplicationRunnerFactoryBean = new TaskJobLauncherApplicationRunnerFactoryBean(jobLauncher, + jobExplorer, jobs, this.properties, jobRegistry, jobRepository, batchProperties); return taskJobLauncherApplicationRunnerFactoryBean; } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunner.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunner.java index 31d02a29..bce53a75 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunner.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunner.java @@ -69,8 +69,7 @@ import org.springframework.util.StringUtils; */ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunner { - private static final Log logger = LogFactory - .getLog(TaskJobLauncherApplicationRunner.class); + private static final Log logger = LogFactory.getLog(TaskJobLauncherApplicationRunner.class); private JobLauncher taskJobLauncher; @@ -93,9 +92,8 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn * @param taskBatchProperties the properties used to configure the * taskBatchProperties. */ - public TaskJobLauncherApplicationRunner(JobLauncher jobLauncher, - JobExplorer jobExplorer, JobRepository jobRepository, - TaskBatchProperties taskBatchProperties) { + public TaskJobLauncherApplicationRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, + JobRepository jobRepository, TaskBatchProperties taskBatchProperties) { super(jobLauncher, jobExplorer, jobRepository); this.taskJobLauncher = jobLauncher; this.taskJobExplorer = jobExplorer; @@ -115,18 +113,14 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn monitorJobExecutions(); } - protected void execute(Job job, JobParameters jobParameters) - throws JobExecutionAlreadyRunningException, JobRestartException, - JobInstanceAlreadyCompleteException, JobParametersInvalidException { + protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, + JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { String jobName = job.getName(); JobParameters parameters = jobParameters; - boolean jobInstanceExists = this.taskJobRepository.isJobInstanceExists(jobName, - parameters); + boolean jobInstanceExists = this.taskJobRepository.isJobInstanceExists(jobName, parameters); if (jobInstanceExists) { - JobExecution lastJobExecution = this.taskJobRepository - .getLastJobExecution(jobName, jobParameters); - if (lastJobExecution != null && isStoppedOrFailed(lastJobExecution) - && job.isRestartable()) { + JobExecution lastJobExecution = this.taskJobRepository.getLastJobExecution(jobName, jobParameters); + if (lastJobExecution != null && isStoppedOrFailed(lastJobExecution) && job.isRestartable()) { // Retry a failed or stopped execution with previous parameters JobParameters previousParameters = lastJobExecution.getJobParameters(); /* @@ -135,8 +129,7 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn * they are required (or need to be modified) on a restart, they need to * be (re)specified. */ - JobParameters previousIdentifyingParameters = removeNonIdentifying( - previousParameters); + JobParameters previousIdentifyingParameters = removeNonIdentifying(previousParameters); // merge additional parameters with previous ones (overriding those with // the same key) parameters = merge(previousIdentifyingParameters, jobParameters); @@ -145,15 +138,14 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn else { JobParametersIncrementer incrementer = job.getJobParametersIncrementer(); if (incrementer != null) { - JobParameters nextParameters = new JobParametersBuilder(jobParameters, - this.taskJobExplorer).getNextJobParameters(job).toJobParameters(); + JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.taskJobExplorer) + .getNextJobParameters(job).toJobParameters(); parameters = merge(nextParameters, jobParameters); } } JobExecution execution = this.taskJobLauncher.run(job, parameters); if (this.taskApplicationEventPublisher != null) { - this.taskApplicationEventPublisher - .publishEvent(new JobExecutionEvent(execution)); + this.taskApplicationEventPublisher.publishEvent(new JobExecutionEvent(execution)); } this.jobExecutionList.add(execution); if (execution.getStatus().equals(BatchStatus.FAILED)) { @@ -171,8 +163,7 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn List failedJobExecutions = new ArrayList<>(); RepeatStatus repeatStatus = RepeatStatus.FINISHED; for (JobExecution jobExecution : this.jobExecutionList) { - JobExecution currentJobExecution = this.taskJobExplorer - .getJobExecution(jobExecution.getId()); + JobExecution currentJobExecution = this.taskJobExplorer.getJobExecution(jobExecution.getId()); BatchStatus batchStatus = currentJobExecution.getStatus(); if (batchStatus.isRunning()) { repeatStatus = RepeatStatus.CONTINUABLE; @@ -183,8 +174,7 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn } Thread.sleep(this.taskBatchProperties.getFailOnJobFailurePollInterval()); - if (repeatStatus.equals(RepeatStatus.FINISHED) - && failedJobExecutions.size() > 0) { + if (repeatStatus.equals(RepeatStatus.FINISHED) && failedJobExecutions.size() > 0) { throwJobFailedException(failedJobExecutions); } return repeatStatus; @@ -194,10 +184,10 @@ public class TaskJobLauncherApplicationRunner extends JobLauncherApplicationRunn private void throwJobFailedException(List failedJobExecutions) { StringBuilder message = new StringBuilder("The following Jobs have failed: \n"); for (JobExecution failedJobExecution : failedJobExecutions) { - message.append(String.format("Job %s failed during " - + "execution for job instance id %s with jobExecutionId of %s \n", - failedJobExecution.getJobInstance().getJobName(), - failedJobExecution.getJobId(), failedJobExecution.getId())); + message.append(String.format( + "Job %s failed during " + "execution for job instance id %s with jobExecutionId of %s \n", + failedJobExecution.getJobInstance().getJobName(), failedJobExecution.getJobId(), + failedJobExecution.getId())); } logger.error(message); diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListener.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListener.java index a57b3305..c1da966f 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListener.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListener.java @@ -32,7 +32,7 @@ import org.springframework.util.Assert; * * @author Michael Minella */ -public class TaskBatchExecutionListener implements JobExecutionListener, Ordered { +public class TaskBatchExecutionListener implements JobExecutionListener, Ordered { private static final Log logger = LogFactory.getLog(TaskBatchExecutionListener.class); @@ -57,12 +57,10 @@ public class TaskBatchExecutionListener implements JobExecutionListener, Ordere @Override public void beforeJob(JobExecution jobExecution) { if (this.taskExecution == null) { - logger.warn( - "This job was executed outside the scope of a task but still used the task listener."); + logger.warn("This job was executed outside the scope of a task but still used the task listener."); } else { - logger.info(String.format( - "The job execution id %s was run within the task execution %s", + logger.info(String.format("The job execution id %s was run within the task execution %s", jobExecution.getId(), this.taskExecution.getExecutionId())); this.taskBatchDao.saveRelationship(this.taskExecution, jobExecution); } @@ -72,4 +70,5 @@ public class TaskBatchExecutionListener implements JobExecutionListener, Ordere public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/JdbcTaskBatchDao.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/JdbcTaskBatchDao.java index 7a6f4580..a2f366db 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/JdbcTaskBatchDao.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/JdbcTaskBatchDao.java @@ -69,8 +69,7 @@ public class JdbcTaskBatchDao implements TaskBatchDao { public void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution) { Assert.notNull(taskExecution, "A taskExecution is required"); Assert.notNull(jobExecution, "A jobExecution is required"); - this.jdbcTemplate.update(getQuery(INSERT_STATEMENT), - taskExecution.getExecutionId(), jobExecution.getId()); + this.jdbcTemplate.update(getQuery(INSERT_STATEMENT), taskExecution.getExecutionId(), jobExecution.getId()); } private String getQuery(String base) { diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/MapTaskBatchDao.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/MapTaskBatchDao.java index fc0be10f..09ae3739 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/MapTaskBatchDao.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/support/MapTaskBatchDao.java @@ -48,8 +48,7 @@ public class MapTaskBatchDao implements TaskBatchDao { Assert.notNull(jobExecution, "A jobExecution is required"); if (this.relationships.containsKey(taskExecution.getExecutionId())) { - this.relationships.get(taskExecution.getExecutionId()) - .add(jobExecution.getId()); + this.relationships.get(taskExecution.getExecutionId()).add(jobExecution.getId()); } else { TreeSet jobExecutionIds = new TreeSet<>(); diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java index c151aced..f50d09c5 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java @@ -74,8 +74,7 @@ import org.springframework.util.CollectionUtils; * @author Michael Minella * @author Glenn Renfro */ -public class DeployerPartitionHandler - implements PartitionHandler, EnvironmentAware, InitializingBean { +public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAware, InitializingBean { /** * ID of Spring Cloud Task job execution. @@ -145,21 +144,23 @@ public class DeployerPartitionHandler private TaskExecutor taskExecutor; - @Autowired private TaskRepository taskRepository; /** * Constructor initializing the DeployerPartitionHandler instance. - * @param taskLauncher The {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute partitioned tasks. + * @param taskLauncher The + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute + * partitioned tasks. * @param jobExplorer The {@link JobExplorer} to acquire the status of the job. * @param resource The {@link Resource} to the app to be launched. * @param stepName The name of the step. - * @param taskExecutor If task launches should occur asynchronously then provide a {@link ThreadPoolTaskExecutor}. Default is null. + * @param taskExecutor If task launches should occur asynchronously then provide a + * {@link ThreadPoolTaskExecutor}. Default is null. */ - public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, JobExplorer jobExplorer, - Resource resource, String stepName, TaskRepository taskRepository, - TaskExecutor taskExecutor) { + public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, + JobExplorer jobExplorer, Resource resource, String stepName, TaskRepository taskRepository, + TaskExecutor taskExecutor) { Assert.notNull(taskLauncher, "A taskLauncher is required"); Assert.notNull(jobExplorer, "A jobExplorer is required"); Assert.notNull(resource, "A resource is required"); @@ -176,13 +177,15 @@ public class DeployerPartitionHandler /** * Constructor initializing the DeployerPartitionHandler instance. - * @param taskLauncher The {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute partitioned tasks. + * @param taskLauncher The + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute + * partitioned tasks. * @param jobExplorer The {@link JobExplorer} to acquire the status of the job. * @param resource The {@link Resource} to the app to be launched. * @param stepName The name of the step. */ - public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, JobExplorer jobExplorer, - Resource resource, String stepName, TaskRepository taskRepository) { + public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, + JobExplorer jobExplorer, Resource resource, String stepName, TaskRepository taskRepository) { this(taskLauncher, jobExplorer, resource, stepName, taskRepository, new SyncTaskExecutor()); } @@ -190,8 +193,7 @@ public class DeployerPartitionHandler * Used to provide any environment variables to be set on each worker launched. * @param environmentVariablesProvider an {@link EnvironmentVariablesProvider} */ - public void setEnvironmentVariablesProvider( - EnvironmentVariablesProvider environmentVariablesProvider) { + public void setEnvironmentVariablesProvider(EnvironmentVariablesProvider environmentVariablesProvider) { this.environmentVariablesProvider = environmentVariablesProvider; } @@ -208,8 +210,7 @@ public class DeployerPartitionHandler * Used to provide any command line arguements to be passed to each worker launched. * @param commandLineArgsProvider {@link CommandLineArgsProvider} */ - public void setCommandLineArgsProvider( - CommandLineArgsProvider commandLineArgsProvider) { + public void setCommandLineArgsProvider(CommandLineArgsProvider commandLineArgsProvider) { this.commandLineArgsProvider = commandLineArgsProvider; } @@ -250,8 +251,10 @@ public class DeployerPartitionHandler } /** - * Map of deployment properties to be used by the {@link org.springframework.cloud.deployer.spi.task.TaskLauncher}. - * @param deploymentProperties properties to be used by the {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} + * Map of deployment properties to be used by the + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher}. + * @param deploymentProperties properties to be used by the + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} */ public void setDeploymentProperties(Map deploymentProperties) { this.deploymentProperties = deploymentProperties; @@ -271,19 +274,17 @@ public class DeployerPartitionHandler this.taskExecution = taskExecution; if (this.commandLineArgsProvider == null) { - SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider( - taskExecution); + SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider(taskExecution); this.commandLineArgsProvider = provider; } } @Override - public Collection handle(StepExecutionSplitter stepSplitter, - StepExecution stepExecution) throws Exception { + public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) + throws Exception { - final Set tempCandidates = stepSplitter.split(stepExecution, - this.gridSize); + final Set tempCandidates = stepSplitter.split(stepExecution, this.gridSize); // Following two lines due to https://jira.spring.io/browse/BATCH-2490 final Set candidates = new HashSet<>(tempCandidates.size()); @@ -306,23 +307,18 @@ public class DeployerPartitionHandler return pollReplies(stepExecution, executed, candidates, partitions); } - private void launchWorkers(Set candidates, - Set executed) { + private void launchWorkers(Set candidates, Set executed) { TaskLauncherHandler taskLauncherHandler = new TaskLauncherHandler(this.commandLineArgsProvider, - this.taskRepository, this.defaultArgsAsEnvironmentVars, - this.stepName, this.taskExecution, this.environmentVariablesProvider, - this.resource, this.deploymentProperties, - this.taskLauncher, - this.applicationName); + this.taskRepository, this.defaultArgsAsEnvironmentVars, this.stepName, this.taskExecution, + this.environmentVariablesProvider, this.resource, this.deploymentProperties, this.taskLauncher, + this.applicationName); for (StepExecution execution : candidates) { if (this.currentWorkers < this.maxWorkers || this.maxWorkers < 0) { if (this.taskExecutor != null) { TaskLauncherHandler taskLauncherThread = new TaskLauncherHandler(this.commandLineArgsProvider, - this.taskRepository, this.defaultArgsAsEnvironmentVars, - this.stepName, this.taskExecution, this.environmentVariablesProvider, - this.resource, this.deploymentProperties, - this.taskLauncher, - this.applicationName, execution); + this.taskRepository, this.defaultArgsAsEnvironmentVars, this.stepName, this.taskExecution, + this.environmentVariablesProvider, this.resource, this.deploymentProperties, + this.taskLauncher, this.applicationName, execution); this.taskExecutor.execute(taskLauncherThread); } else { @@ -335,8 +331,7 @@ public class DeployerPartitionHandler } private Collection pollReplies(final StepExecution masterStepExecution, - final Set executed, final Set candidates, - final int size) throws Exception { + final Set executed, final Set candidates, final int size) throws Exception { final Collection result = new ArrayList<>(executed.size()); @@ -348,8 +343,7 @@ public class DeployerPartitionHandler for (StepExecution curStepExecution : executed) { if (!result.contains(curStepExecution)) { StepExecution partitionStepExecution = DeployerPartitionHandler.this.jobExplorer - .getStepExecution(masterStepExecution.getJobExecutionId(), - curStepExecution.getId()); + .getStepExecution(masterStepExecution.getJobExecutionId(), curStepExecution.getId()); BatchStatus batchStatus = partitionStepExecution.getStatus(); if (batchStatus != null && isComplete(batchStatus)) { @@ -388,8 +382,7 @@ public class DeployerPartitionHandler } private boolean isComplete(BatchStatus status) { - return status.equals(BatchStatus.COMPLETED) - || status.isGreaterThan(BatchStatus.STARTED); + return status.equals(BatchStatus.COMPLETED) || status.isGreaterThan(BatchStatus.STARTED); } @Override @@ -400,9 +393,9 @@ public class DeployerPartitionHandler @Override public void afterPropertiesSet() throws Exception { if (this.environmentVariablesProvider == null) { - this.environmentVariablesProvider = new SimpleEnvironmentVariablesProvider( - this.environment); + this.environmentVariablesProvider = new SimpleEnvironmentVariablesProvider(this.environment); } } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java index 1363b1e4..56124116 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java @@ -70,8 +70,7 @@ public class DeployerStepExecutionHandler implements CommandLineRunner { private StepLocator stepLocator; - public DeployerStepExecutionHandler(BeanFactory beanFactory, JobExplorer jobExplorer, - JobRepository jobRepository) { + public DeployerStepExecutionHandler(BeanFactory beanFactory, JobExplorer jobExplorer, JobRepository jobRepository) { Assert.notNull(beanFactory, "A beanFactory is required"); Assert.notNull(jobExplorer, "A jobExplorer is required"); Assert.notNull(jobRepository, "A jobRepository is required"); @@ -88,26 +87,23 @@ public class DeployerStepExecutionHandler implements CommandLineRunner { validateRequest(); - Long jobExecutionId = Long.parseLong(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)); - Long stepExecutionId = Long.parseLong(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)); - StepExecution stepExecution = this.jobExplorer.getStepExecution(jobExecutionId, - stepExecutionId); + Long jobExecutionId = Long + .parseLong(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)); + Long stepExecutionId = Long + .parseLong(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)); + StepExecution stepExecution = this.jobExplorer.getStepExecution(jobExecutionId, stepExecutionId); if (stepExecution == null) { - throw new NoSuchStepException(String.format( - "No StepExecution could be located for step execution id %s within job execution %s", - stepExecutionId, jobExecutionId)); + throw new NoSuchStepException( + String.format("No StepExecution could be located for step execution id %s within job execution %s", + stepExecutionId, jobExecutionId)); } - String stepName = this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME); + String stepName = this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME); Step step = this.stepLocator.getStep(stepName); try { - this.logger.debug(String.format( - "Executing step %s with step execution id %s and job execution id %s", + this.logger.debug(String.format("Executing step %s with step execution id %s and job execution id %s", stepExecution.getStepName(), stepExecutionId, jobExecutionId)); step.execute(stepExecution); @@ -124,23 +120,16 @@ public class DeployerStepExecutionHandler implements CommandLineRunner { } private void validateRequest() { - Assert.isTrue( - this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID), + Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID), "A job execution id is required"); - Assert.isTrue( - this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID), + Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID), "A step execution id is required"); - Assert.isTrue( - this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME), + Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME), "A step name is required"); Assert.isTrue( this.stepLocator.getStepNames() - .contains(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)), + .contains(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)), "The step requested cannot be found in the provided BeanFactory"); } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java index f4f4ee14..bdc696b3 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java @@ -36,8 +36,7 @@ public class NoOpEnvironmentVariablesProvider implements EnvironmentVariablesPro * @return an empty {@link Map} */ @Override - public Map getEnvironmentVariables( - ExecutionContext executionContext) { + public Map getEnvironmentVariables(ExecutionContext executionContext) { return Collections.emptyMap(); } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java index 204b43c9..b5f34b85 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java @@ -71,11 +71,9 @@ public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesP } @Override - public Map getEnvironmentVariables( - ExecutionContext executionContext) { + public Map getEnvironmentVariables(ExecutionContext executionContext) { - Map environmentProperties = new HashMap<>( - this.environmentProperties.size()); + Map environmentProperties = new HashMap<>(this.environmentProperties.size()); if (this.includeCurrentEnvironment) { environmentProperties.putAll(getCurrentEnvironmentProperties()); @@ -91,11 +89,9 @@ public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesP Set keys = new HashSet<>(); - for (PropertySource propertySource : ((AbstractEnvironment) this.environment) - .getPropertySources()) { + for (PropertySource propertySource : ((AbstractEnvironment) this.environment).getPropertySources()) { if (propertySource instanceof MapPropertySource) { - keys.addAll(Arrays - .asList(((MapPropertySource) propertySource).getPropertyNames())); + keys.addAll(Arrays.asList(((MapPropertySource) propertySource).getPropertyNames())); } } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java index a2e1afeb..4ec6d08d 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java @@ -64,26 +64,32 @@ public class TaskLauncherHandler implements Runnable { private Log logger = LogFactory.getLog(TaskLauncherHandler.class); /** - * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides command line - * arguments passed to each partition's execution. - * @param taskRepository The {@link TaskRepository} task repository for launching the partition. - * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are used - * internally by Spring Cloud Task and Spring Batch are passed as environment variables instead of command line arguments. + * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides + * command line arguments passed to each partition's execution. + * @param taskRepository The {@link TaskRepository} task repository for launching the + * partition. + * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are + * used internally by Spring Cloud Task and Spring Batch are passed as environment + * variables instead of command line arguments. * @param stepName The name of the step. * @param taskExecution The {@link TaskExecution} to be associated with the partition. - * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that provides the environmennt variables. + * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that + * provides the environmennt variables. * @param resource The {@link Resource} to be launched. - * @param deploymentProperties The {@link Map} containing the deployment properties for the partition. - * @param taskLauncher {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to launch the partition. + * @param deploymentProperties The {@link Map} containing the deployment properties + * for the partition. + * @param taskLauncher + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to + * launch the partition. * @param applicationName The name to be associated with task. * @param workerStepExecution The {@link StepExecution} for the paritition. */ - public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, - TaskRepository taskRepository, boolean defaultArgsAsEnvironmentVars, - String stepName, TaskExecution taskExecution, EnvironmentVariablesProvider - environmentVariablesProvider, Resource resource, Map deploymentProperties, - org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, - String applicationName, StepExecution workerStepExecution) { + public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, TaskRepository taskRepository, + boolean defaultArgsAsEnvironmentVars, String stepName, TaskExecution taskExecution, + EnvironmentVariablesProvider environmentVariablesProvider, Resource resource, + Map deploymentProperties, + org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, String applicationName, + StepExecution workerStepExecution) { this.commandLineArgsProvider = commandLineArgsProvider; this.taskRepository = taskRepository; this.defaultArgsAsEnvironmentVars = defaultArgsAsEnvironmentVars; @@ -98,25 +104,30 @@ public class TaskLauncherHandler implements Runnable { } /** - * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides command line - * arguments passed to each partition's execution. - * @param taskRepository The {@link TaskRepository} task repository for launching the partition. - * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are used - * internally by Spring Cloud Task and Spring Batch are passed as environment variables instead of command line arguments. + * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides + * command line arguments passed to each partition's execution. + * @param taskRepository The {@link TaskRepository} task repository for launching the + * partition. + * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are + * used internally by Spring Cloud Task and Spring Batch are passed as environment + * variables instead of command line arguments. * @param stepName The name of the step. * @param taskExecution The {@link TaskExecution} to be associated with the partition. - * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that provides the environmennt variables. + * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that + * provides the environmennt variables. * @param resource The {@link Resource} to be launched. - * @param deploymentProperties The {@link Map} containing the deployment properties for the partition. - * @param taskLauncher {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to launch the partition. + * @param deploymentProperties The {@link Map} containing the deployment properties + * for the partition. + * @param taskLauncher + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to + * launch the partition. * @param applicationName The name to be associated with task. */ - public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, - TaskRepository taskRepository, boolean defaultArgsAsEnvironmentVars, - String stepName, TaskExecution taskExecution, EnvironmentVariablesProvider - environmentVariablesProvider, Resource resource, Map deploymentProperties, - org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, - String applicationName) { + public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, TaskRepository taskRepository, + boolean defaultArgsAsEnvironmentVars, String stepName, TaskExecution taskExecution, + EnvironmentVariablesProvider environmentVariablesProvider, Resource resource, + Map deploymentProperties, + org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, String applicationName) { this.commandLineArgsProvider = commandLineArgsProvider; this.taskRepository = taskRepository; this.defaultArgsAsEnvironmentVars = defaultArgsAsEnvironmentVars; @@ -134,7 +145,6 @@ public class TaskLauncherHandler implements Runnable { launchWorker(this.workerStepExecution); } - /** * Launches the partition for the StepExecution. * @param workerStepExecution The {@link StepExecution} @@ -142,8 +152,7 @@ public class TaskLauncherHandler implements Runnable { public void launchWorker(StepExecution workerStepExecution) { List arguments = new ArrayList<>(); - ExecutionContext copyContext = new ExecutionContext( - workerStepExecution.getExecutionContext()); + ExecutionContext copyContext = new ExecutionContext(workerStepExecution.getExecutionContext()); arguments.addAll(this.commandLineArgsProvider.getCommandLineArgs(copyContext)); @@ -153,69 +162,61 @@ public class TaskLauncherHandler implements Runnable { partitionTaskExecution = this.taskRepository.createTaskExecution(); } else { - logger.warn( - "TaskRepository was not set so external execution id will not be recorded."); + logger.warn("TaskRepository was not set so external execution id will not be recorded."); } if (!this.defaultArgsAsEnvironmentVars) { arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, - String.valueOf(workerStepExecution.getJobExecution().getId()))); + String.valueOf(workerStepExecution.getJobExecution().getId()))); arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, - String.valueOf(workerStepExecution.getId()))); + String.valueOf(workerStepExecution.getId()))); arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, this.stepName)); - arguments - .add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME, + arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME, String.format("%s_%s_%s", this.taskExecution.getTaskName(), - workerStepExecution.getJobExecution().getJobInstance() - .getJobName(), - workerStepExecution.getStepName()))); + workerStepExecution.getJobExecution().getJobInstance().getJobName(), + workerStepExecution.getStepName()))); arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, - String.valueOf(this.taskExecution.getExecutionId()))); + String.valueOf(this.taskExecution.getExecutionId()))); if (partitionTaskExecution != null) { arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID, - String.valueOf(partitionTaskExecution.getExecutionId()))); + String.valueOf(partitionTaskExecution.getExecutionId()))); } } copyContext = new ExecutionContext(workerStepExecution.getExecutionContext()); Map environmentVariables = this.environmentVariablesProvider - .getEnvironmentVariables(copyContext); + .getEnvironmentVariables(copyContext); if (this.defaultArgsAsEnvironmentVars) { environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, - String.valueOf(workerStepExecution.getJobExecution().getId())); + String.valueOf(workerStepExecution.getJobExecution().getId())); environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, - String.valueOf(workerStepExecution.getId())); + String.valueOf(workerStepExecution.getId())); environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, this.stepName); - environmentVariables - .put(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME, + environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME, String.format("%s_%s_%s", this.taskExecution.getTaskName(), - workerStepExecution.getJobExecution().getJobInstance() - .getJobName(), - workerStepExecution.getStepName())); + workerStepExecution.getJobExecution().getJobInstance().getJobName(), + workerStepExecution.getStepName())); environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, - String.valueOf(this.taskExecution.getExecutionId())); + String.valueOf(this.taskExecution.getExecutionId())); environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID, - String.valueOf(partitionTaskExecution.getExecutionId())); + String.valueOf(partitionTaskExecution.getExecutionId())); } - AppDefinition definition = new AppDefinition(resolveApplicationName(), - environmentVariables); + AppDefinition definition = new AppDefinition(resolveApplicationName(), environmentVariables); - AppDeploymentRequest request = new AppDeploymentRequest(definition, this.resource, - this.deploymentProperties, arguments); + AppDeploymentRequest request = new AppDeploymentRequest(definition, this.resource, this.deploymentProperties, + arguments); if (logger.isDebugEnabled()) { - logger.debug( - "Requesting the launch of the following application: " + request); + logger.debug("Requesting the launch of the following application: " + request); } String externalExecutionId = this.taskLauncher.launch(request); if (this.taskRepository != null) { - this.taskRepository.updateExternalExecutionId( - partitionTaskExecution.getExecutionId(), externalExecutionId); + this.taskRepository.updateExternalExecutionId(partitionTaskExecution.getExecutionId(), externalExecutionId); } } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java index 22ea4373..5d8acbd4 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java @@ -37,63 +37,48 @@ import static org.assertj.core.api.Assertions.assertThat; public class TaskJobLauncherAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, - TaskJobLauncherAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(BatchAutoConfiguration.class, TaskJobLauncherAutoConfiguration.class)) .withUserConfiguration(TaskBatchExecutionListenerTests.JobConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, EmbeddedDataSourceConfiguration.class); @Test public void testAutoBuiltDataSourceWithTaskJobLauncherCLR() { - this.contextRunner - .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true") - .run(context -> { - assertThat(context) - .hasSingleBean(TaskJobLauncherApplicationRunner.class); - assertThat(context.getBean(TaskJobLauncherApplicationRunner.class) - .getOrder()).isEqualTo(0); - }); + this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true").run(context -> { + assertThat(context).hasSingleBean(TaskJobLauncherApplicationRunner.class); + assertThat(context.getBean(TaskJobLauncherApplicationRunner.class).getOrder()).isEqualTo(0); + }); } @Test public void testAutoBuiltDataSourceWithTaskJobLauncherCLROrder() { - this.contextRunner - .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", - "spring.cloud.task.batch.commandLineRunnerOrder=100") - .run(context -> { - assertThat(context.getBean(TaskJobLauncherApplicationRunner.class) - .getOrder()).isEqualTo(100); + this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", + "spring.cloud.task.batch.commandLineRunnerOrder=100").run(context -> { + assertThat(context.getBean(TaskJobLauncherApplicationRunner.class).getOrder()).isEqualTo(100); }); } @Test public void testAutoBuiltDataSourceWithBatchJobNames() { - this.contextRunner - .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", - "spring.batch.job.name=job1", - "spring.cloud.task.batch.jobName=foobar") - .run(context -> { + this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", + "spring.batch.job.name=job1", "spring.cloud.task.batch.jobName=foobar").run(context -> { validateJobNames(context, "job1"); }); } @Test public void testAutoBuiltDataSourceWithTaskBatchJobNames() { - this.contextRunner - .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", - "spring.cloud.task.batch.jobNames=job1,job2") - .run(context -> { + this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", + "spring.cloud.task.batch.jobNames=job1,job2").run(context -> { validateJobNames(context, "job1,job2"); }); } - private void validateJobNames(AssertableApplicationContext context, String jobNames) - throws Exception { + private void validateJobNames(AssertableApplicationContext context, String jobNames) throws Exception { JobLauncherApplicationRunner jobLauncherApplicationRunner = context .getBean(TaskJobLauncherApplicationRunner.class); - Object names = ReflectionTestUtils.getField(jobLauncherApplicationRunner, - "jobName"); + Object names = ReflectionTestUtils.getField(jobLauncherApplicationRunner, "jobName"); assertThat(names).isEqualTo(jobNames); } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java index 5c368a6b..2a3fda66 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java @@ -70,8 +70,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Glenn Renfro */ @ExtendWith(SpringExtension.class) -@ContextConfiguration( - classes = { TaskJobLauncherApplicationRunnerCoreTests.BatchConfiguration.class }) +@ContextConfiguration(classes = { TaskJobLauncherApplicationRunnerCoreTests.BatchConfiguration.class }) public class TaskJobLauncherApplicationRunnerCoreTests { @Autowired @@ -103,8 +102,8 @@ public class TaskJobLauncherApplicationRunnerCoreTests { Tasklet tasklet = (contribution, chunkContext) -> RepeatStatus.FINISHED; this.step = this.steps.get("step").tasklet(tasklet).build(); this.job = this.jobs.get("job").start(this.step).build(); - this.runner = new TaskJobLauncherApplicationRunner(this.jobLauncher, - this.jobExplorer, this.jobRepository, new TaskBatchProperties()); + this.runner = new TaskJobLauncherApplicationRunner(this.jobLauncher, this.jobExplorer, this.jobRepository, + new TaskBatchProperties()); } @@ -113,26 +112,23 @@ public class TaskJobLauncherApplicationRunnerCoreTests { 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()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @DirtiesContext -// @Test + // @Test public void incrementExistingExecution() throws Exception { - this.job = this.jobs.get("job").start(this.step) - .incrementer(new RunIdIncrementer()).build(); + this.job = this.jobs.get("job").start(this.step).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @DirtiesContext -// @Test + // @Test public void retryFailedExecution() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + 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()); @@ -142,16 +138,13 @@ public class TaskJobLauncherApplicationRunnerCoreTests { @DirtiesContext @Test public void runDifferentInstances() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()).build(); + 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(); + 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(); + JobParameters otherJobParameters = new JobParametersBuilder().addString("name", "bar").toJobParameters(); runFailedJob(otherJobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @@ -160,8 +153,8 @@ public class TaskJobLauncherApplicationRunnerCoreTests { @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(); + .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 @@ -171,40 +164,35 @@ public class TaskJobLauncherApplicationRunnerCoreTests { // 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) + assertThatExceptionOfType(JobRestartException.class).isThrownBy(executable::execute) .withMessage("JobInstance already exists and is not restartable"); } @DirtiesContext @Test public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + 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(); + 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()); + runFailedJob(new JobParametersBuilder(jobParameters).addLong("run.id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } @DirtiesContext @Test - public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() - throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() 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(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) + .toJobParameters(); runFailedJob(jobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); // try to re-run a failed execution with non identifying parameters - runFailedJob(new JobParametersBuilder().addLong("run.id", 1L) - .addLong("id", 2L, false).addLong("foo", 3L, false).toJobParameters()); + runFailedJob(new JobParametersBuilder().addLong("run.id", 1L).addLong("id", 2L, false).addLong("foo", 3L, false) + .toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); JobInstance jobInstance = jobExplorer.getLastJobInstance("job"); @@ -212,7 +200,7 @@ public class TaskJobLauncherApplicationRunnerCoreTests { assertThat(executions).hasSize(2); - JobExecution firstJobExecution = executions.get(0); + JobExecution firstJobExecution = executions.get(0); JobExecution secondJobExecution = executions.get(1); if ((executions.get(0).getId() > executions.get(1).getId())) { firstJobExecution = executions.get(1); @@ -261,7 +249,7 @@ public class TaskJobLauncherApplicationRunnerCoreTests { private JobRepository jobRepository; @Autowired - private DataSource dataSource; + private DataSource dataSource; public BatchConfiguration() throws Exception { } @@ -317,7 +305,7 @@ public class TaskJobLauncherApplicationRunnerCoreTests { databasePopulator.addScript(new ClassPathResource("org/springframework/batch/core/schema-drop-h2.sql")); dataSourceInitializer.setDatabaseCleaner(databasePopulator); return dataSourceInitializer; - } + } } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java index adef16d0..4201103d 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java @@ -84,10 +84,8 @@ public class TaskJobLauncherApplicationRunnerTests { @Test public void testTaskJobLauncherCLRSuccessFail() { - String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true" }; - validateForFail(DEFAULT_ERROR_MESSAGE, - TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class, + String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true" }; + validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class, enabledArgs); } @@ -97,45 +95,37 @@ public class TaskJobLauncherApplicationRunnerTests { */ @Test public void testTaskJobLauncherCLRSuccessFailWithAnnotation() { - String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true" }; + String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true" }; validateForFail(DEFAULT_ERROR_MESSAGE, - TaskJobLauncherApplicationRunnerTests.JobWithFailureAnnotatedConfiguration.class, - enabledArgs); + TaskJobLauncherApplicationRunnerTests.JobWithFailureAnnotatedConfiguration.class, enabledArgs); } @Test public void testTaskJobLauncherCLRSuccessFailWithTaskExecutor() { - String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true", + String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", "--spring.cloud.task.batch.failOnJobFailurePollInterval=500" }; validateForFail(DEFAULT_ERROR_MESSAGE, - TaskJobLauncherApplicationRunnerTests.JobWithFailureTaskExecutorConfiguration.class, - enabledArgs); + TaskJobLauncherApplicationRunnerTests.JobWithFailureTaskExecutorConfiguration.class, enabledArgs); } @Test public void testNoTaskJobLauncher() { - String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true", - "--spring.cloud.task.batch.failOnJobFailurePollInterval=500", - "--spring.batch.job.enabled=false" }; - this.applicationContext = SpringApplication.run(new Class[] { - TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class }, - enabledArgs); + String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", + "--spring.cloud.task.batch.failOnJobFailurePollInterval=500", "--spring.batch.job.enabled=false" }; + this.applicationContext = SpringApplication.run( + new Class[] { TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class }, enabledArgs); JobExplorer jobExplorer = this.applicationContext.getBean(JobExplorer.class); assertThat(jobExplorer.getJobNames().size()).isEqualTo(0); } @Test public void testTaskJobLauncherPickOneJob() { - String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.fail-on-job-failure=true", + String[] enabledArgs = new String[] { "--spring.cloud.task.batch.fail-on-job-failure=true", "--spring.cloud.task.batch.jobNames=jobSucceed" }; boolean isExceptionThrown = false; try { - this.applicationContext = SpringApplication.run(new Class[] { - TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class }, + this.applicationContext = SpringApplication.run( + new Class[] { TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class }, enabledArgs); } catch (IllegalStateException exception) { @@ -148,19 +138,15 @@ public class TaskJobLauncherApplicationRunnerTests { @Test public void testApplicationRunnerSetToFalse() { String[] enabledArgs = new String[] {}; - this.applicationContext = SpringApplication.run( - new Class[] { - TaskJobLauncherApplicationRunnerTests.JobConfiguration.class }, - enabledArgs); + this.applicationContext = SpringApplication + .run(new Class[] { TaskJobLauncherApplicationRunnerTests.JobConfiguration.class }, enabledArgs); validateContext(); - assertThat(this.applicationContext.getBean(JobLauncherApplicationRunner.class)) - .isNotNull(); + assertThat(this.applicationContext.getBean(JobLauncherApplicationRunner.class)).isNotNull(); - Executable executable = () -> this.applicationContext - .getBean(TaskJobLauncherApplicationRunner.class); + Executable executable = () -> this.applicationContext.getBean(TaskJobLauncherApplicationRunner.class); - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(executable::execute).withMessage("No qualifying bean of type " + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(executable::execute) + .withMessage("No qualifying bean of type " + "'org.springframework.cloud.task.batch.handler.TaskJobLauncherApplicationRunner' available"); validateContext(); } @@ -168,24 +154,21 @@ public class TaskJobLauncherApplicationRunnerTests { private void validateContext() { TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(1); - assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()) - .getExecutionId()).isEqualTo(1); + assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1); } private void validateForFail(String errorMessage, Class clazz, String[] enabledArgs) { - Executable executable = () -> this.applicationContext = SpringApplication.run( - new Class[] { clazz, PropertyPlaceholderAutoConfiguration.class }, - enabledArgs); + Executable executable = () -> this.applicationContext = SpringApplication + .run(new Class[] { clazz, PropertyPlaceholderAutoConfiguration.class }, enabledArgs); - assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(executable::execute).has(new Condition() { + assertThatExceptionOfType(IllegalStateException.class).isThrownBy(executable::execute) + .has(new Condition() { @Override public boolean matches(Throwable value) { return errorMessage.equals(value.getCause().getMessage()); @@ -207,23 +190,20 @@ public class TaskJobLauncherApplicationRunnerTests { @Bean public Job job() { - return this.jobBuilderFactory.get("job") - .start(this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) { - System.out.println("Executed"); - return RepeatStatus.FINISHED; - } - }).build()).build(); + return this.jobBuilderFactory.get("job").start(this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) { + System.out.println("Executed"); + return RepeatStatus.FINISHED; + } + }).build()).build(); } } @EnableBatchProcessing - @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, - BatchAutoConfiguration.class, TaskBatchAutoConfiguration.class, - TaskJobLauncherAutoConfiguration.class, SingleTaskConfiguration.class, + @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, + TaskBatchAutoConfiguration.class, TaskJobLauncherAutoConfiguration.class, SingleTaskConfiguration.class, SimpleTaskAutoConfiguration.class }) @Import(EmbeddedDataSourceConfiguration.class) @EnableTask @@ -237,24 +217,21 @@ public class TaskJobLauncherApplicationRunnerTests { @Bean public Job jobFail() { - return this.jobBuilderFactory.get("jobA") - .start(this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - System.out.println("Executed"); - throw new IllegalStateException("WHOOPS"); - } - }).build()).build(); + return this.jobBuilderFactory.get("jobA").start(this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + System.out.println("Executed"); + throw new IllegalStateException("WHOOPS"); + } + }).build()).build(); } @Bean public Job jobFun() { - return this.jobBuilderFactory.get("jobSucceed").start( - this.stepBuilderFactory.get("step1Succeed").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("jobSucceed") + .start(this.stepBuilderFactory.get("step1Succeed").tasklet(new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) { + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) { System.out.println("Executed"); return RepeatStatus.FINISHED; } @@ -264,8 +241,7 @@ public class TaskJobLauncherApplicationRunnerTests { } @EnableTask - public static class JobWithFailureAnnotatedConfiguration - extends JobWithFailureConfiguration { + public static class JobWithFailureAnnotatedConfiguration extends JobWithFailureConfiguration { } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java index 451735a5..82b8f405 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java @@ -56,8 +56,7 @@ public class PrefixTests { @Test public void testPrefix() { - this.applicationContext = SpringApplication.run(JobConfiguration.class, - "--spring.cloud.task.tablePrefix=FOO_"); + this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.tablePrefix=FOO_"); TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); @@ -74,8 +73,8 @@ public class PrefixTests { @Bean public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) { - return jobBuilderFactory.get("job").start(stepBuilderFactory - .get("step1").tasklet((contribution, chunkContext) -> { + return jobBuilderFactory.get("job") + .start(stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> { System.out.println("Executed"); return RepeatStatus.FINISHED; }).build()).build(); @@ -83,8 +82,8 @@ public class PrefixTests { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().addScript("classpath:schema-h2.sql") - .setType(EmbeddedDatabaseType.H2).build(); + return new EmbeddedDatabaseBuilder().addScript("classpath:schema-h2.sql").setType(EmbeddedDatabaseType.H2) + .build(); } } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java index 10fbbad1..dde5f04b 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java @@ -133,23 +133,20 @@ public class TaskBatchExecutionListenerTests { @Test public void testFactoryBean() { - this.applicationContext = SpringApplication.run(JobFactoryBeanConfiguration.class, - ARGS); + this.applicationContext = SpringApplication.run(JobFactoryBeanConfiguration.class, ARGS); validateContext(); } private void validateContext() { TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(1); - assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()) - .getExecutionId()).isEqualTo(1); + assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1); } @@ -158,27 +155,24 @@ public class TaskBatchExecutionListenerTests { this.applicationContext = SpringApplication.run(TaskNotEnabledConfiguration.class, ARGS); assertThat(applicationContext.getBean(Job.class)).isNotNull(); assertThatThrownBy(() -> applicationContext.getBean(TaskBatchExecutionListenerBeanPostProcessor.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); assertThatThrownBy(() -> applicationContext.getBean(TaskBatchExecutionListener.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); } @Test public void testMultipleDataSources() { - this.applicationContext = SpringApplication - .run(JobConfigurationMultipleDataSources.class, ARGS); + this.applicationContext = SpringApplication.run(JobConfigurationMultipleDataSources.class, ARGS); TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(1); - assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()) - .getExecutionId()).isEqualTo(1); + assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1); } @Test @@ -187,11 +181,10 @@ public class TaskBatchExecutionListenerTests { TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(0); } @@ -202,36 +195,30 @@ public class TaskBatchExecutionListenerTests { TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(1); - assertThat((long) taskExplorer - .getTaskExecutionIdByJobExecutionId(jobExecutionIds.iterator().next())) - .isEqualTo(1); + assertThat((long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIds.iterator().next())) + .isEqualTo(1); } @Test public void testMultipleJobs() { - this.applicationContext = SpringApplication.run(MultipleJobConfiguration.class, - "--spring.batch.job.name=job1"); + this.applicationContext = SpringApplication.run(MultipleJobConfiguration.class, "--spring.batch.job.name=job1"); TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class); - Page page = taskExplorer.findTaskExecutionsByName("application", - PageRequest.of(0, 1)); + Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1)); - Set jobExecutionIds = taskExplorer.getJobExecutionIdsByTaskExecutionId( - page.iterator().next().getExecutionId()); + Set jobExecutionIds = taskExplorer + .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId()); assertThat(jobExecutionIds.size()).isEqualTo(1); Iterator jobExecutionIdsIterator = jobExecutionIds.iterator(); - assertThat((long) taskExplorer - .getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())) - .isEqualTo(1); + assertThat((long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())).isEqualTo(1); } @@ -242,23 +229,19 @@ public class TaskBatchExecutionListenerTests { jobNames.add("job2"); jobNames.add("TESTOBJECT"); - TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor( - jobNames); + TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor(jobNames); SimpleJob testObject = new SimpleJob(); - SimpleJob bean = (SimpleJob) beanPostProcessor - .postProcessBeforeInitialization(testObject, "TESTOBJECT"); + SimpleJob bean = (SimpleJob) beanPostProcessor.postProcessBeforeInitialization(testObject, "TESTOBJECT"); assertThat(bean).isEqualTo(testObject); } @Test public void testBatchExecutionListenerBeanPostProcessorWithEmptyJobNames() { - TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor( - Collections.emptyList()); + TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor(Collections.emptyList()); SimpleJob testObject = new SimpleJob(); - SimpleJob bean = (SimpleJob) beanPostProcessor - .postProcessBeforeInitialization(testObject, "TESTOBJECT"); + SimpleJob bean = (SimpleJob) beanPostProcessor.postProcessBeforeInitialization(testObject, "TESTOBJECT"); assertThat(bean).isEqualTo(testObject); } @@ -269,12 +252,10 @@ public class TaskBatchExecutionListenerTests { }); } - private TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor( - List jobNames) { - this.applicationContext = SpringApplication.run(new Class[] { - JobConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TaskBatchAutoConfiguration.class, SimpleTaskAutoConfiguration.class, + private TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor(List jobNames) { + this.applicationContext = SpringApplication.run(new Class[] { JobConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TaskBatchAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class }, ARGS); TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = this.applicationContext @@ -329,10 +310,10 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job() { return this.jobBuilderFactory.get("job") - .start(this.stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> { - System.out.println("Executed"); - return RepeatStatus.FINISHED; - }).build()).build(); + .start(this.stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> { + System.out.println("Executed"); + return RepeatStatus.FINISHED; + }).build()).build(); } } @@ -355,8 +336,8 @@ public class TaskBatchExecutionListenerTests { @Override public Job getObject() { return JobFactoryBeanConfiguration.this.jobBuilderFactory.get("job") - .start(JobFactoryBeanConfiguration.this.stepBuilderFactory - .get("step1").tasklet((contribution, chunkContext) -> { + .start(JobFactoryBeanConfiguration.this.stepBuilderFactory.get("step1") + .tasklet((contribution, chunkContext) -> { System.out.println("Executed"); return RepeatStatus.FINISHED; }).build()) @@ -383,32 +364,29 @@ public class TaskBatchExecutionListenerTests { @Import(EmbeddedDataSourceConfiguration.class) public static class JobConfigurationMultipleDataSources { - @Bean public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) { - return jobBuilderFactory.get("job") - .start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - System.out.println("Executed"); - return RepeatStatus.FINISHED; - } - }).build()).build(); + return jobBuilderFactory.get("job").start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + System.out.println("Executed"); + return RepeatStatus.FINISHED; + } + }).build()).build(); } @Bean @Primary public DataSource myDataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2).setName("myDataSource"); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .setName("myDataSource"); return builder.build(); } @Bean public DataSource incorrectDataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2).setName("incorrectDataSource"); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .setName("incorrectDataSource"); return builder.build(); } @@ -438,8 +416,8 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job1() { - return this.jobBuilderFactory.get("job1").start( - this.stepBuilderFactory.get("job1step1").tasklet((contribution, chunkContext) -> { + return this.jobBuilderFactory.get("job1") + .start(this.stepBuilderFactory.get("job1step1").tasklet((contribution, chunkContext) -> { System.out.println("Executed job1"); return RepeatStatus.FINISHED; }).build()).build(); @@ -447,8 +425,8 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job2() { - return this.jobBuilderFactory.get("job2").start( - this.stepBuilderFactory.get("job2step1").tasklet((contribution, chunkContext) -> { + return this.jobBuilderFactory.get("job2") + .start(this.stepBuilderFactory.get("job2step1").tasklet((contribution, chunkContext) -> { System.out.println("Executed job2"); return RepeatStatus.FINISHED; }).build()).build(); diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java index 5e18b9d3..2d3e1b66 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java @@ -91,49 +91,43 @@ public class DeployerPartitionHandlerTests { public void setUp() { MockitoAnnotations.openMocks(this); this.environment = new MockEnvironment(); - TaskExecution taskExecution = new TaskExecution(2, 0, "name", new Date(), - new Date(), "", Collections.emptyList(), null, null, null); - Mockito.lenient().when(taskRepository.createTaskExecution()) - .thenReturn(taskExecution); + TaskExecution taskExecution = new TaskExecution(2, 0, "name", new Date(), new Date(), "", + Collections.emptyList(), null, null, null); + Mockito.lenient().when(taskRepository.createTaskExecution()).thenReturn(taskExecution); } @Test public void testDeprecatedConstructorValidation() { - validateDeprecatedConstructorValidation(null, null, null, null, - "A taskLauncher is required"); - validateDeprecatedConstructorValidation(this.taskLauncher, null, null, null, - "A jobExplorer is required"); - validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, null, - null, "A resource is required"); - validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, - this.resource, null, "A step name is required"); + validateDeprecatedConstructorValidation(null, null, null, null, "A taskLauncher is required"); + validateDeprecatedConstructorValidation(this.taskLauncher, null, null, null, "A jobExplorer is required"); + validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, + "A resource is required"); + validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, + "A step name is required"); - new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, - "step-name", this.taskRepository); + new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step-name", + this.taskRepository); } @Test public void testConstructorValidation() { - validateConstructorValidation(null, null, null, null, null, - "A taskLauncher is required"); - validateConstructorValidation(this.taskLauncher, null, null, null, null, - "A jobExplorer is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, - null, "A resource is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, - null, null, "A step name is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, - null, null, "A step name is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, - "step-name", null, "A TaskRepository is required"); - new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, - "step-name", this.taskRepository); + validateConstructorValidation(null, null, null, null, null, "A taskLauncher is required"); + validateConstructorValidation(this.taskLauncher, null, null, null, null, "A jobExplorer is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, null, "A resource is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, null, + "A step name is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, null, + "A step name is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, "step-name", null, + "A TaskRepository is required"); + new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step-name", + this.taskRepository); } @Test public void testNoPartitions() throws Exception { - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); StepExecution stepExecution = new StepExecution("step1", new JobExecution(1L)); @@ -153,11 +147,11 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); TaskExecution taskExecution = new TaskExecution(); @@ -167,18 +161,15 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); @@ -188,16 +179,14 @@ public class DeployerPartitionHandlerTests { AppDefinition appDefinition = request.getDefinition(); assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); assertThat(request.getCommandlineArguments() - .contains(formatArgs("spring.cloud.task.executionid", "2"))).isTrue(); + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); + assertThat(request.getCommandlineArguments().contains(formatArgs("spring.cloud.task.executionid", "2"))) + .isTrue(); assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); @@ -212,33 +201,30 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setDefaultArgsAsEnvironmentVars(true); - TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, - new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, new ArrayList<>(), null, + null); taskExecution.setTaskName("partitionedJobTask"); Set stepExecutions = new HashSet<>(); stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); @@ -250,23 +236,17 @@ public class DeployerPartitionHandlerTests { assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); assertThat(request.getCommandlineArguments().isEmpty()).isTrue(); assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .isEqualTo("1"); + .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).isEqualTo("1"); assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .isEqualTo("4"); + .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)).isEqualTo("4"); + assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .isEqualTo("step1"); + assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME)) + .isEqualTo("partitionedJobTask_partitionedJob_step1:partition1"); assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .isEqualTo("step1"); - assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME)) - .isEqualTo("partitionedJobTask_partitionedJob_step1:partition1"); - assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID)) - .isEqualTo("55"); - assertThat(request.getDefinition().getProperties() - .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID)) - .isEqualTo("2"); + .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID)).isEqualTo("55"); + assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID)) + .isEqualTo("2"); assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); @@ -281,15 +261,15 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); - TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, - new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, new ArrayList<>(), null, + null); taskExecution.setTaskName("partitionedJobTask"); @@ -297,8 +277,7 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); @@ -306,13 +285,11 @@ public class DeployerPartitionHandlerTests { handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, "55"))) - .isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, "55"))).isTrue(); } @Test @@ -336,19 +313,19 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart3 = getStepExecutionStart(jobExecution, 6L); - StepExecution workerStepExecutionFinish3 = getStepExecutionFinish( - workerStepExecutionStart3, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish3 = getStepExecutionFinish(workerStepExecutionStart3, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository, threadPoolTaskExecutor); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository, threadPoolTaskExecutor); handler.setEnvironment(this.environment); TaskExecution taskExecution = new TaskExecution(); @@ -362,24 +339,18 @@ public class DeployerPartitionHandlerTests { when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); - when(this.jobExplorer.getStepExecution(1L, 6L)) - .thenReturn(workerStepExecutionFinish3); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 6L)).thenReturn(workerStepExecutionFinish3); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); Thread.sleep(5000); - verify(this.taskLauncher, times(3)) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher, times(3)).launch(this.appDeploymentRequestArgumentCaptor.capture()); - List allValues = this.appDeploymentRequestArgumentCaptor - .getAllValues(); + List allValues = this.appDeploymentRequestArgumentCaptor.getAllValues(); validateAppDeploymentRequests(allValues, 3); @@ -393,19 +364,19 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart3 = getStepExecutionStart(jobExecution, 6L); - StepExecution workerStepExecutionFinish3 = getStepExecutionFinish( - workerStepExecutionStart3, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish3 = getStepExecutionFinish(workerStepExecutionStart3, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setMaxWorkers(2); @@ -420,24 +391,18 @@ public class DeployerPartitionHandlerTests { when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); - when(this.jobExplorer.getStepExecution(1L, 6L)) - .thenReturn(workerStepExecutionFinish3); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 6L)).thenReturn(workerStepExecutionFinish3); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher, times(3)) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher, times(3)).launch(this.appDeploymentRequestArgumentCaptor.capture()); - List allValues = this.appDeploymentRequestArgumentCaptor - .getAllValues(); + List allValues = this.appDeploymentRequestArgumentCaptor.getAllValues(); validateAppDeploymentRequests(allValues, 3); @@ -451,19 +416,19 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.FAILED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.FAILED); StepExecution workerStepExecutionStart3 = getStepExecutionStart(jobExecution, 6L); - StepExecution workerStepExecutionFinish3 = getStepExecutionFinish( - workerStepExecutionStart3, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish3 = getStepExecutionFinish(workerStepExecutionStart3, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setMaxWorkers(2); @@ -478,24 +443,18 @@ public class DeployerPartitionHandlerTests { when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); - when(this.jobExplorer.getStepExecution(1L, 6L)) - .thenReturn(workerStepExecutionFinish3); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 6L)).thenReturn(workerStepExecutionFinish3); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher, times(3)) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher, times(3)).launch(this.appDeploymentRequestArgumentCaptor.capture()); - List allValues = this.appDeploymentRequestArgumentCaptor - .getAllValues(); + List allValues = this.appDeploymentRequestArgumentCaptor.getAllValues(); validateAppDeploymentRequests(allValues, 3); @@ -524,11 +483,11 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); Map environmentParameters = new HashMap<>(2); environmentParameters.put("foo", "bar"); @@ -546,17 +505,14 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); @@ -568,14 +524,12 @@ public class DeployerPartitionHandlerTests { AppDefinition appDefinition = request.getDefinition(); assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); @@ -593,11 +547,11 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); Map environmentParameters = new HashMap<>(2); @@ -616,17 +570,14 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); @@ -634,20 +585,17 @@ public class DeployerPartitionHandlerTests { assertThat(request.getDefinition().getProperties().size()).isEqualTo(3); assertThat(request.getDefinition().getProperties().get("foo")).isEqualTo("bar"); assertThat(request.getDefinition().getProperties().get("baz")).isEqualTo("qux"); - assertThat(request.getDefinition().getProperties().get("task")) - .isEqualTo("batch"); + assertThat(request.getDefinition().getProperties().get("task")).isEqualTo("batch"); AppDefinition appDefinition = request.getDefinition(); assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); @@ -662,15 +610,15 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setPollInterval(20000L); @@ -684,33 +632,26 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart2); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); Date startTime = new Date(); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); Date endTime = new Date(); - verify(this.taskLauncher, times(2)) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher, times(2)).launch(this.appDeploymentRequestArgumentCaptor.capture()); - List allRequests = this.appDeploymentRequestArgumentCaptor - .getAllValues(); + List allRequests = this.appDeploymentRequestArgumentCaptor.getAllValues(); validateAppDeploymentRequests(allRequests, 2); validateStepExecutionResults(results); assertThat(endTime.getTime() - startTime.getTime() >= 19999) - .as("Time difference was too small: " - + (endTime.getTime() - startTime.getTime())) - .isTrue(); + .as("Time difference was too small: " + (endTime.getTime() - startTime.getTime())).isTrue(); } @Test @@ -720,15 +661,15 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setPollInterval(20000L); @@ -743,10 +684,8 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart2); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - Mockito.lenient().when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + Mockito.lenient().when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); handler.afterPropertiesSet(); @@ -764,15 +703,15 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish1 = getStepExecutionFinish( - workerStepExecutionStart1, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1, + BatchStatus.COMPLETED); StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L); - StepExecution workerStepExecutionFinish2 = getStepExecutionFinish( - workerStepExecutionStart2, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); handler.setGridSize(2); @@ -785,23 +724,18 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart2); when(this.splitter.split(masterStepExecution, 2)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish1); - when(this.jobExplorer.getStepExecution(1L, 5L)) - .thenReturn(workerStepExecutionFinish2); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1); + when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher, times(2)) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher, times(2)).launch(this.appDeploymentRequestArgumentCaptor.capture()); - List allRequests = this.appDeploymentRequestArgumentCaptor - .getAllValues(); + List allRequests = this.appDeploymentRequestArgumentCaptor.getAllValues(); validateAppDeploymentRequests(allRequests, 2); @@ -815,11 +749,11 @@ public class DeployerPartitionHandlerTests { JobExecution jobExecution = masterStepExecution.getJobExecution(); StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L); - StepExecution workerStepExecutionFinish = getStepExecutionFinish( - workerStepExecutionStart, BatchStatus.COMPLETED); + StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart, + BatchStatus.COMPLETED); - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, - this.jobExplorer, this.resource, "step1", this.taskRepository); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, + this.resource, "step1", this.taskRepository); handler.setEnvironment(this.environment); Map deploymentProperties = new HashMap<>(2); @@ -835,17 +769,14 @@ public class DeployerPartitionHandlerTests { stepExecutions.add(workerStepExecutionStart); when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions); - when(this.jobExplorer.getStepExecution(1L, 4L)) - .thenReturn(workerStepExecutionFinish); + when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish); handler.afterPropertiesSet(); handler.beforeTask(taskExecution); - Collection results = handler.handle(this.splitter, - masterStepExecution); + Collection results = handler.handle(this.splitter, masterStepExecution); - verify(this.taskLauncher) - .launch(this.appDeploymentRequestArgumentCaptor.capture()); + verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture()); AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue(); @@ -857,14 +788,12 @@ public class DeployerPartitionHandlerTests { AppDefinition appDefinition = request.getDefinition(); assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))) - .isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))).isTrue(); + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); @@ -876,18 +805,16 @@ public class DeployerPartitionHandlerTests { return String.format("--%s=%s", key, value); } - private StepExecution getStepExecutionFinish(StepExecution stepExecutionStart, - BatchStatus status) { - StepExecution workerStepExecutionFinish = new StepExecution( - stepExecutionStart.getStepName(), stepExecutionStart.getJobExecution()); + private StepExecution getStepExecutionFinish(StepExecution stepExecutionStart, BatchStatus status) { + StepExecution workerStepExecutionFinish = new StepExecution(stepExecutionStart.getStepName(), + stepExecutionStart.getJobExecution()); workerStepExecutionFinish.setId(stepExecutionStart.getId()); workerStepExecutionFinish.setStatus(status); return workerStepExecutionFinish; } private StepExecution getStepExecutionStart(JobExecution jobExecution, long id) { - StepExecution workerStepExecutionStart = new StepExecution( - "step1:partition" + (id - 3), jobExecution); + StepExecution workerStepExecutionStart = new StepExecution("step1:partition" + (id - 3), jobExecution); workerStepExecutionStart.setId(id); return workerStepExecutionStart; } @@ -917,8 +844,7 @@ public class DeployerPartitionHandlerTests { } } - private void validateAppDeploymentRequests(List allRequests, - int numberOfPartitions) { + private void validateAppDeploymentRequests(List allRequests, int numberOfPartitions) { Collections.sort(allRequests, new Comparator() { @Override public int compare(AppDeploymentRequest o1, AppDeploymentRequest o2) { @@ -926,8 +852,7 @@ public class DeployerPartitionHandlerTests { String o1Command = ""; for (String commandlineArgument : commandlineArguments) { - if (commandlineArgument.contains( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) { + if (commandlineArgument.contains(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) { o1Command = commandlineArgument; break; } @@ -937,8 +862,7 @@ public class DeployerPartitionHandlerTests { String o2Command = ""; for (String commandlineArgument : commandlineArguments) { - if (commandlineArgument.contains( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) { + if (commandlineArgument.contains(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) { o2Command = commandlineArgument; break; } @@ -955,39 +879,32 @@ public class DeployerPartitionHandlerTests { AppDefinition appDefinition = request.getDefinition(); assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))) + assertThat(request.getCommandlineArguments() + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue(); + assertThat(request.getCommandlineArguments().contains( + formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, String.valueOf(i)))) .isTrue(); assertThat(request.getCommandlineArguments() - .contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, - String.valueOf(i)))).isTrue(); - assertThat(request.getCommandlineArguments().contains(formatArgs( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))) - .isTrue(); - assertThat(request.getCommandlineArguments() - .contains(formatArgs("spring.cloud.task.executionid", "2"))).isTrue(); + .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue(); + assertThat(request.getCommandlineArguments().contains(formatArgs("spring.cloud.task.executionid", "2"))) + .isTrue(); } } - private void validateDeprecatedConstructorValidation(TaskLauncher taskLauncher, - JobExplorer jobExplorer, Resource resource, String stepName, - String expectedMessage) { + private void validateDeprecatedConstructorValidation(TaskLauncher taskLauncher, JobExplorer jobExplorer, + Resource resource, String stepName, String expectedMessage) { try { - new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, stepName, - this.taskRepository); + new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, stepName, this.taskRepository); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage()).isEqualTo(expectedMessage); } } - private void validateConstructorValidation(TaskLauncher taskLauncher, - JobExplorer jobExplorer, Resource resource, String stepName, - TaskRepository taskRepository, String expectedMessage) { + private void validateConstructorValidation(TaskLauncher taskLauncher, JobExplorer jobExplorer, Resource resource, + String stepName, TaskRepository taskRepository, String expectedMessage) { try { - new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, stepName, - taskRepository); + new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, stepName, taskRepository); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage()).isEqualTo(expectedMessage); diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandlerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandlerTests.java index 36002208..a9e519f8 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandlerTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandlerTests.java @@ -71,8 +71,7 @@ public class DeployerStepExecutionHandlerTests { public void setUp() { MockitoAnnotations.openMocks(this); - this.handler = new DeployerStepExecutionHandler(this.beanFactory, - this.jobExplorer, this.jobRepository); + this.handler = new DeployerStepExecutionHandler(this.beanFactory, this.jobExplorer, this.jobRepository); ReflectionTestUtils.setField(this.handler, "environment", this.environment); } @@ -80,113 +79,80 @@ public class DeployerStepExecutionHandlerTests { @Test public void testConstructorValidation() { validateConstructorValidation(null, null, null, "A beanFactory is required"); - validateConstructorValidation(this.beanFactory, null, null, - "A jobExplorer is required"); - validateConstructorValidation(this.beanFactory, this.jobExplorer, null, - "A jobRepository is required"); + validateConstructorValidation(this.beanFactory, null, null, "A jobExplorer is required"); + validateConstructorValidation(this.beanFactory, this.jobExplorer, null, "A jobRepository is required"); - new DeployerStepExecutionHandler(this.beanFactory, this.jobExplorer, - this.jobRepository); + new DeployerStepExecutionHandler(this.beanFactory, this.jobExplorer, this.jobRepository); } @Test public void testValidationOfRequestValuesExist() throws Exception { validateEnvironmentConfiguration("A job execution id is required", new String[0]); - validateEnvironmentConfiguration("A step execution id is required", new String[] { - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID }); + validateEnvironmentConfiguration("A step execution id is required", + new String[] { DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID }); validateEnvironmentConfiguration("A step name is required", - new String[] { - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, + new String[] { DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID }); } @Test public void testValidationOfRequestStepFound() throws Exception { - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn(true); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn(true); - when(this.environment - .containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn(true); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("foo"); - when(this.beanFactory.getBeanNamesForType(Step.class)) - .thenReturn(new String[] { "bar", "baz" }); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn(true); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn("foo"); + when(this.beanFactory.getBeanNamesForType(Step.class)).thenReturn(new String[] { "bar", "baz" }); try { this.handler.run(); } catch (IllegalArgumentException iae) { - assertThat(iae.getMessage()).isEqualTo( - "The step requested cannot be found in the provided BeanFactory"); + assertThat(iae.getMessage()).isEqualTo("The step requested cannot be found in the provided BeanFactory"); } } @Test public void testMissingStepExecution() throws Exception { - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn(true); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn(true); - when(this.environment - .containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn(true); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("foo"); - when(this.beanFactory.getBeanNamesForType(Step.class)) - .thenReturn(new String[] { "foo", "bar", "baz" }); - when(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn("2"); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn("1"); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn(true); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn("foo"); + when(this.beanFactory.getBeanNamesForType(Step.class)).thenReturn(new String[] { "foo", "bar", "baz" }); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn("2"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).thenReturn("1"); try { this.handler.run(); } catch (NoSuchStepException nsse) { - assertThat(nsse.getMessage()).isEqualTo( - "No StepExecution could be located for step execution id 2 within job execution 1"); + assertThat(nsse.getMessage()) + .isEqualTo("No StepExecution could be located for step execution id 2 within job execution 1"); } } @Test public void testRunSuccessful() throws Exception { - StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), - 2L); + StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), 2L); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn(true); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn(true); - when(this.environment - .containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn(true); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); - when(this.beanFactory.getBeanNamesForType(Step.class)) - .thenReturn(new String[] { "workerStep", "foo", "bar" }); - when(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn("2"); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn("1"); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn(true); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); + when(this.beanFactory.getBeanNamesForType(Step.class)).thenReturn(new String[] { "workerStep", "foo", "bar" }); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn("2"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).thenReturn("1"); when(this.jobExplorer.getStepExecution(1L, 2L)).thenReturn(workerStep); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); when(this.beanFactory.getBean("workerStep", Step.class)).thenReturn(this.step); this.handler.run(); @@ -197,74 +163,50 @@ public class DeployerStepExecutionHandlerTests { @Test public void testJobInterruptedException() throws Exception { - StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), - 2L); + StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), 2L); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn(true); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn(true); - when(this.environment - .containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn(true); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); - when(this.beanFactory.getBeanNamesForType(Step.class)) - .thenReturn(new String[] { "workerStep", "foo", "bar" }); - when(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn("2"); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn("1"); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn(true); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); + when(this.beanFactory.getBeanNamesForType(Step.class)).thenReturn(new String[] { "workerStep", "foo", "bar" }); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn("2"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).thenReturn("1"); when(this.jobExplorer.getStepExecution(1L, 2L)).thenReturn(workerStep); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); when(this.beanFactory.getBean("workerStep", Step.class)).thenReturn(this.step); - doThrow(new JobInterruptedException("expected")).when(this.step) - .execute(workerStep); + doThrow(new JobInterruptedException("expected")).when(this.step).execute(workerStep); this.handler.run(); verify(this.jobRepository).update(this.stepExecutionArgumentCaptor.capture()); - assertThat(this.stepExecutionArgumentCaptor.getValue().getStatus()) - .isEqualTo(BatchStatus.STOPPED); + assertThat(this.stepExecutionArgumentCaptor.getValue().getStatus()).isEqualTo(BatchStatus.STOPPED); } @Test public void testRuntimeException() throws Exception { - StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), - 2L); + StepExecution workerStep = new StepExecution("workerStep", new JobExecution(1L), 2L); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn(true); - when(this.environment.containsProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn(true); - when(this.environment - .containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn(true); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); - when(this.beanFactory.getBeanNamesForType(Step.class)) - .thenReturn(new String[] { "workerStep", "foo", "bar" }); - when(this.environment.getProperty( - DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) - .thenReturn("2"); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) - .thenReturn("1"); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn(true); + when(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)).thenReturn(true); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); + when(this.beanFactory.getBeanNamesForType(Step.class)).thenReturn(new String[] { "workerStep", "foo", "bar" }); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)) + .thenReturn("2"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).thenReturn("1"); when(this.jobExplorer.getStepExecution(1L, 2L)).thenReturn(workerStep); - when(this.environment - .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) - .thenReturn("workerStep"); + when(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)) + .thenReturn("workerStep"); when(this.beanFactory.getBean("workerStep", Step.class)).thenReturn(this.step); doThrow(new RuntimeException("expected")).when(this.step).execute(workerStep); @@ -272,12 +214,10 @@ public class DeployerStepExecutionHandlerTests { verify(this.jobRepository).update(this.stepExecutionArgumentCaptor.capture()); - assertThat(this.stepExecutionArgumentCaptor.getValue().getStatus()) - .isEqualTo(BatchStatus.FAILED); + assertThat(this.stepExecutionArgumentCaptor.getValue().getStatus()).isEqualTo(BatchStatus.FAILED); } - private void validateEnvironmentConfiguration(String errorMessage, - String[] properties) throws Exception { + private void validateEnvironmentConfiguration(String errorMessage, String[] properties) throws Exception { for (String property : properties) { when(this.environment.containsProperty(property)).thenReturn(true); @@ -291,8 +231,8 @@ public class DeployerStepExecutionHandlerTests { } } - private void validateConstructorValidation(BeanFactory beanFactory, - JobExplorer jobExplorer, JobRepository jobRepository, String message) { + private void validateConstructorValidation(BeanFactory beanFactory, JobExplorer jobExplorer, + JobRepository jobRepository, String message) { try { new DeployerStepExecutionHandler(beanFactory, jobExplorer, jobRepository); } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProviderTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProviderTests.java index 4058527f..866d5d2c 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProviderTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProviderTests.java @@ -37,13 +37,11 @@ public class NoOpEnvironmentVariablesProviderTests { @Test public void test() { - Map environmentVariables = this.provider - .getEnvironmentVariables(null); + Map environmentVariables = this.provider.getEnvironmentVariables(null); assertThat(environmentVariables).isNotNull(); assertThat(environmentVariables.isEmpty()).isTrue(); - Map environmentVariables2 = this.provider - .getEnvironmentVariables(null); + Map environmentVariables2 = this.provider.getEnvironmentVariables(null); assertThat(environmentVariables == environmentVariables2).isTrue(); } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProviderTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProviderTests.java index 7196f586..703defd0 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProviderTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProviderTests.java @@ -36,8 +36,7 @@ public class SimpleCommandLineArgsProviderTests { TaskExecution taskExecution = new TaskExecution(); taskExecution.setArguments(Arrays.asList("foo", "bar", "baz")); - SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider( - taskExecution); + SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider(taskExecution); List commandLineArgs = provider.getCommandLineArgs(null); @@ -56,8 +55,7 @@ public class SimpleCommandLineArgsProviderTests { TaskExecution taskExecution = new TaskExecution(); taskExecution.setArguments(Arrays.asList("foo", "bar", "baz")); - SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider( - taskExecution); + SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider(taskExecution); provider.setAppendedArgs(appendedValues); List commandLineArgs = provider.getCommandLineArgs(null); @@ -76,8 +74,7 @@ public class SimpleCommandLineArgsProviderTests { TaskExecution taskExecution = new TaskExecution(); taskExecution.setArguments(Arrays.asList("foo", "bar", "baz")); - SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider( - taskExecution); + SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider(taskExecution); provider.setAppendedArgs(null); List commandLineArgs = provider.getCommandLineArgs(null); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurer.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurer.java index a6ffaca7..0a56fb00 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurer.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurer.java @@ -96,16 +96,14 @@ public class DefaultTaskConfigurer implements TaskConfigurer { * infrastructure. * @param context the context to be used. */ - public DefaultTaskConfigurer(DataSource dataSource, String tablePrefix, - ApplicationContext context) { + public DefaultTaskConfigurer(DataSource dataSource, String tablePrefix, ApplicationContext context) { this.dataSource = dataSource; this.context = context; TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean; if (this.dataSource != null) { - taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource, - tablePrefix); + taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource, tablePrefix); } else { taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(); @@ -136,27 +134,22 @@ public class DefaultTaskConfigurer implements TaskConfigurer { if (isDataSourceAvailable()) { try { Class.forName("javax.persistence.EntityManager"); - if (this.context != null && this.context - .getBeanNamesForType(EntityManager.class).length > 0) { - logger.debug( - "EntityManager was found, using JpaTransactionManager"); + if (this.context != null && this.context.getBeanNamesForType(EntityManager.class).length > 0) { + logger.debug("EntityManager was found, using JpaTransactionManager"); this.transactionManager = new JpaTransactionManager(); } } catch (ClassNotFoundException ignore) { - logger.debug( - "No EntityManager was found, using DataSourceTransactionManager"); + logger.debug("No EntityManager was found, using DataSourceTransactionManager"); } finally { if (this.transactionManager == null) { - this.transactionManager = new DataSourceTransactionManager( - this.dataSource); + this.transactionManager = new DataSourceTransactionManager(this.dataSource); } } } else { - logger.debug( - "No DataSource was found, using ResourcelessTransactionManager"); + logger.debug("No DataSource was found, using ResourcelessTransactionManager"); this.transactionManager = new ResourcelessTransactionManager(); } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SimpleTaskAutoConfiguration.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SimpleTaskAutoConfiguration.java index 0a56db02..413b5872 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SimpleTaskAutoConfiguration.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SimpleTaskAutoConfiguration.java @@ -55,13 +55,12 @@ import org.springframework.util.CollectionUtils; @EnableTransactionManagement @EnableConfigurationProperties({ TaskProperties.class }) // @checkstyle:off -@ConditionalOnProperty(prefix = "spring.cloud.task.autoconfiguration", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.cloud.task.autoconfiguration", name = "enabled", havingValue = "true", + matchIfMissing = true) // @checkstyle:on public class SimpleTaskAutoConfiguration { - protected static final Log logger = LogFactory - .getLog(SimpleTaskAutoConfiguration.class); + protected static final Log logger = LogFactory.getLog(SimpleTaskAutoConfiguration.class); @Autowired(required = false) private Collection dataSources; @@ -85,7 +84,6 @@ public class SimpleTaskAutoConfiguration { return this.taskRepository; } - @Bean public PlatformTransactionManager springCloudTaskTransactionManager() { return this.platformTransactionManager; @@ -104,8 +102,7 @@ public class SimpleTaskAutoConfiguration { @Bean @Lazy(false) public TaskRepositoryInitializer taskRepositoryInitializer() { - TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer( - this.taskProperties); + TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(this.taskProperties); DataSource initializerDataSource = getDefaultConfigurer().getTaskDataSource(); if (initializerDataSource != null) { taskRepositoryInitializer.setDataSource(initializerDataSource); @@ -114,7 +111,6 @@ public class SimpleTaskAutoConfiguration { return taskRepositoryInitializer; } - @Bean @Profile("cloud") TaskObservationCloudKeyValues taskObservationCloudKeyValues() { @@ -132,8 +128,7 @@ public class SimpleTaskAutoConfiguration { TaskConfigurer taskConfigurer = getDefaultConfigurer(); - logger.debug(String.format("Using %s TaskConfigurer", - taskConfigurer.getClass().getName())); + logger.debug(String.format("Using %s TaskConfigurer", taskConfigurer.getClass().getName())); this.taskRepository = taskConfigurer.getTaskRepository(); this.platformTransactionManager = taskConfigurer.getTransactionManager(); @@ -148,18 +143,14 @@ public class SimpleTaskAutoConfiguration { if (configurers < 1) { TaskConfigurer taskConfigurer; - if (!CollectionUtils.isEmpty(this.dataSources) - && this.dataSources.size() == 1) { - taskConfigurer = new DefaultTaskConfigurer( - this.dataSources.iterator().next(), + if (!CollectionUtils.isEmpty(this.dataSources) && this.dataSources.size() == 1) { + taskConfigurer = new DefaultTaskConfigurer(this.dataSources.iterator().next(), this.taskProperties.getTablePrefix(), this.context); } else { - taskConfigurer = new DefaultTaskConfigurer( - this.taskProperties.getTablePrefix()); + taskConfigurer = new DefaultTaskConfigurer(this.taskProperties.getTablePrefix()); } - this.context.getBeanFactory().registerSingleton("taskConfigurer", - taskConfigurer); + this.context.getBeanFactory().registerSingleton("taskConfigurer", taskConfigurer); return taskConfigurer; } else { @@ -167,8 +158,7 @@ public class SimpleTaskAutoConfiguration { return this.context.getBean(TaskConfigurer.class); } else { - throw new IllegalStateException( - "Expected one TaskConfigurer but found " + configurers); + throw new IllegalStateException("Expected one TaskConfigurer but found " + configurers); } } } @@ -177,14 +167,12 @@ public class SimpleTaskAutoConfiguration { int configurers = this.context.getBeanNamesForType(TaskConfigurer.class).length; // retrieve the count of dataSources (without instantiating them) excluding // DataSource proxy beans - long dataSources = Arrays - .stream(this.context.getBeanNamesForType(DataSource.class)) + long dataSources = Arrays.stream(this.context.getBeanNamesForType(DataSource.class)) .filter((name -> !ScopedProxyUtils.isScopedTarget(name))).count(); if (configurers == 0 && dataSources > 1) { - throw new IllegalStateException( - "To use the default TaskConfigurer the context must contain no more than" - + " one DataSource, found " + dataSources); + throw new IllegalStateException("To use the default TaskConfigurer the context must contain no more than" + + " one DataSource, found " + dataSources); } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SingleInstanceTaskListener.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SingleInstanceTaskListener.java index 03d2e4fb..44b14022 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SingleInstanceTaskListener.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/SingleInstanceTaskListener.java @@ -73,29 +73,27 @@ public class SingleInstanceTaskListener implements ApplicationListener applicationArguments, - @Autowired(required = false) ObservationRegistry observationRegistry, - @Autowired(required = false) TaskObservationCloudKeyValues taskObservationCloudKeyValues) { + public TaskLifecycleConfiguration(TaskProperties taskProperties, ConfigurableApplicationContext context, + TaskRepository taskRepository, TaskExplorer taskExplorer, TaskNameResolver taskNameResolver, + ObjectProvider applicationArguments, + @Autowired(required = false) ObservationRegistry observationRegistry, + @Autowired(required = false) TaskObservationCloudKeyValues taskObservationCloudKeyValues) { this.taskProperties = taskProperties; this.context = context; @@ -96,11 +94,10 @@ public class TaskLifecycleConfiguration { @PostConstruct protected void initialize() { if (!this.initialized) { - this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, - this.taskNameResolver, this.applicationArguments, this.taskExplorer, - this.taskProperties, - new TaskListenerExecutorObjectFactory(this.context), - this.observationRegistry, taskObservationCloudKeyValues); + this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, this.taskNameResolver, + this.applicationArguments, this.taskExplorer, this.taskProperties, + new TaskListenerExecutorObjectFactory(this.context), this.observationRegistry, + taskObservationCloudKeyValues); this.initialized = true; } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskObservationCloudKeyValues.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskObservationCloudKeyValues.java index 335c1a33..8aed94ee 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskObservationCloudKeyValues.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskObservationCloudKeyValues.java @@ -103,4 +103,5 @@ public class TaskObservationCloudKeyValues { public void setInstanceIndex(String instanceIndex) { this.instanceIndex = instanceIndex; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/DefaultTaskObservationConvention.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/DefaultTaskObservationConvention.java index 52c9b75c..f89a4130 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/DefaultTaskObservationConvention.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/DefaultTaskObservationConvention.java @@ -36,4 +36,5 @@ public class DefaultTaskObservationConvention implements TaskObservationConventi public String getName() { return "spring.cloud.task.runner"; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationApplicationRunner.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationApplicationRunner.java index ef7b1f2a..8ef9474a 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationApplicationRunner.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationApplicationRunner.java @@ -51,8 +51,9 @@ class ObservationApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { TaskObservationContext context = new TaskObservationContext(this.beanName); - Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION.observation(this.taskObservationConvention, INSTANCE, context, registry()) - .contextualName(this.beanName); + Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION + .observation(this.taskObservationConvention, INSTANCE, context, registry()) + .contextualName(this.beanName); try (Observation.Scope scope = observation.start().openScope()) { this.delegate.run(args); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationCommandLineRunner.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationCommandLineRunner.java index 68af6c06..79da48b5 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationCommandLineRunner.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationCommandLineRunner.java @@ -50,8 +50,9 @@ class ObservationCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { TaskObservationContext context = new TaskObservationContext(this.beanName); - Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION.observation(this.taskObservationConvention, INSTANCE, context, registry()) - .contextualName(this.beanName); + Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION + .observation(this.taskObservationConvention, INSTANCE, context, registry()) + .contextualName(this.beanName); try (Observation.Scope scope = observation.start().openScope()) { this.delegate.run(args); } @@ -70,4 +71,5 @@ class ObservationCommandLineRunner implements CommandLineRunner { } return this.registry; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationTaskAutoConfiguration.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationTaskAutoConfiguration.java index e6cd84b3..3ae80663 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationTaskAutoConfiguration.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/ObservationTaskAutoConfiguration.java @@ -39,12 +39,14 @@ import org.springframework.context.annotation.Configuration; public class ObservationTaskAutoConfiguration { @Bean - static ObservationCommandLineRunnerBeanPostProcessor observedCommandLineRunnerBeanPostProcessor(BeanFactory beanFactory) { + static ObservationCommandLineRunnerBeanPostProcessor observedCommandLineRunnerBeanPostProcessor( + BeanFactory beanFactory) { return new ObservationCommandLineRunnerBeanPostProcessor(beanFactory); } @Bean - static ObservationApplicationRunnerBeanPostProcessor observedApplicationRunnerBeanPostProcessor(BeanFactory beanFactory) { + static ObservationApplicationRunnerBeanPostProcessor observedApplicationRunnerBeanPostProcessor( + BeanFactory beanFactory) { return new ObservationApplicationRunnerBeanPostProcessor(beanFactory); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskDocumentedObservation.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskDocumentedObservation.java index 511e1942..38133630 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskDocumentedObservation.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskDocumentedObservation.java @@ -57,5 +57,7 @@ enum TaskDocumentedObservation implements DocumentedObservation { return "spring.cloud.task.runner.bean-name"; } } + } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationContext.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationContext.java index 5a74a117..707aa0db 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationContext.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationContext.java @@ -35,4 +35,5 @@ public class TaskObservationContext extends Observation.Context { public String getBeanName() { return beanName; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationConvention.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationConvention.java index 5fda2390..f826419c 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationConvention.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/observation/TaskObservationConvention.java @@ -30,4 +30,5 @@ public interface TaskObservationConvention extends Observation.ObservationConven default boolean supportsContext(Observation.Context context) { return context instanceof TaskObservationContext; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/DefaultTaskExecutionObservationConvention.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/DefaultTaskExecutionObservationConvention.java index 046434d7..45341c0d 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/DefaultTaskExecutionObservationConvention.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/DefaultTaskExecutionObservationConvention.java @@ -21,8 +21,7 @@ import io.micrometer.common.KeyValues; import org.springframework.cloud.task.repository.TaskExecution; /** - * /** - * Default {@link TaskExecutionObservationConvention} implementation. + * /** Default {@link TaskExecutionObservationConvention} implementation. * * @author Glenn Renfro * @since 3.0.0 @@ -41,15 +40,16 @@ public class DefaultTaskExecutionObservationConvention implements TaskExecutionO private KeyValues getKeyValuesForTaskExecution(TaskExecutionObservationContext context) { TaskExecution execution = context.getTaskExecution(); - return KeyValues.of( - TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), context.getStatus(), - TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), String.valueOf(execution.getExitCode()), - TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), - String.valueOf(execution.getExecutionId())); + return KeyValues.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), context.getStatus(), + TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), + String.valueOf(execution.getExitCode()), + TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), + String.valueOf(execution.getExecutionId())); } @Override public String getName() { return "spring.cloud.task"; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListenerSupport.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListenerSupport.java index 79229ed9..08286955 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListenerSupport.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListenerSupport.java @@ -22,7 +22,8 @@ package org.springframework.cloud.task.listener; * * @author Michael Minella * @since 1.2 - * @deprecated since 3.0 in favor of the default implementations of {@link TaskExecutionListener} + * @deprecated since 3.0 in favor of the default implementations of + * {@link TaskExecutionListener} */ @Deprecated public class TaskExecutionListenerSupport implements TaskExecutionListener { diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservation.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservation.java index a1d55277..d2f51360 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservation.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservation.java @@ -27,6 +27,7 @@ import io.micrometer.observation.docs.DocumentedObservation; * @since 3.0.0 */ public enum TaskExecutionObservation implements DocumentedObservation { + /** * Metrics created around a task execution. */ @@ -41,6 +42,7 @@ public enum TaskExecutionObservation implements DocumentedObservation { return "spring.cloud.task"; } }; + @Override public KeyName[] getLowCardinalityKeyNames() { return TaskKeyValues.values(); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationContext.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationContext.java index 41ac8c7e..4ca36dba 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationContext.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationContext.java @@ -28,6 +28,7 @@ import org.springframework.cloud.task.repository.TaskExecution; * @since 3.0.0 */ public class TaskExecutionObservationContext extends Observation.Context { + private final TaskExecution taskExecution; private String exceptionMessage = "none"; @@ -57,4 +58,5 @@ public class TaskExecutionObservationContext extends Observation.Context { public void setStatus(String status) { this.status = status; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationConvention.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationConvention.java index 0ede4ff7..fc4525bf 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationConvention.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionObservationConvention.java @@ -24,10 +24,12 @@ import io.micrometer.observation.Observation; * @author Glenn Renfro * @since 3.0.0 */ -public interface TaskExecutionObservationConvention extends Observation.ObservationConvention { +public interface TaskExecutionObservationConvention + extends Observation.ObservationConvention { @Override default boolean supportsContext(Observation.Context context) { return context instanceof TaskExecutionObservationContext; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskLifecycleListener.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskLifecycleListener.java index cf9d048f..925b0cba 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskLifecycleListener.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskLifecycleListener.java @@ -80,8 +80,8 @@ import org.springframework.util.StringUtils; * @author Michael Minella * @author Glenn Renfro */ -public class TaskLifecycleListener implements ApplicationListener, - SmartLifecycle, DisposableBean, Ordered { +public class TaskLifecycleListener + implements ApplicationListener, SmartLifecycle, DisposableBean, Ordered { private static final Log logger = LogFactory.getLog(TaskLifecycleListener.class); @@ -135,18 +135,16 @@ public class TaskLifecycleListener implements ApplicationListener(); this.taskListenerExecutorObjectFactory.getObject(); if (!CollectionUtils.isEmpty(this.taskExecutionListenersFromContext)) { - this.taskExecutionListeners - .addAll(this.taskExecutionListenersFromContext); + this.taskExecutionListeners.addAll(this.taskExecutionListenersFromContext); } - this.taskExecutionListeners - .add(this.taskListenerExecutorObjectFactory.getObject()); + this.taskExecutionListeners.add(this.taskListenerExecutorObjectFactory.getObject()); List args = new ArrayList<>(0); @@ -282,35 +272,27 @@ public class TaskLifecycleListener implements ApplicationListener startupListenerList = new ArrayList<>( - this.taskExecutionListeners); + List startupListenerList = new ArrayList<>(this.taskExecutionListeners); if (!CollectionUtils.isEmpty(startupListenerList)) { try { Collections.reverse(startupListenerList); @@ -360,8 +341,8 @@ public class TaskLifecycleListener implements ApplicationListener { +public class TaskListenerExecutorObjectFactory implements ObjectFactory { private static final Log logger = LogFactory.getLog(TaskListenerExecutor.class); - private final Set> nonAnnotatedClasses = Collections - .newSetFromMap(new ConcurrentHashMap<>()); + private final Set> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>()); private ConfigurableApplicationContext context; @@ -75,8 +73,7 @@ public class TaskListenerExecutorObjectFactory this.afterTaskInstances = new HashMap<>(); this.failedTaskInstances = new HashMap<>(); initializeExecutor(); - return new TaskListenerExecutor(this.beforeTaskInstances, this.afterTaskInstances, - this.failedTaskInstances); + return new TaskListenerExecutor(this.beforeTaskInstances, this.afterTaskInstances, this.failedTaskInstances); } private void initializeExecutor() { @@ -92,8 +89,7 @@ public class TaskListenerExecutorObjectFactory // An unresolvable bean type, probably from a lazy bean - let's ignore // it. if (logger.isDebugEnabled()) { - logger.debug("Could not resolve target class for bean with name '" - + beanName + "'", ex); + logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex); } } if (type != null) { @@ -105,10 +101,7 @@ public class TaskListenerExecutorObjectFactory catch (RuntimeException ex) { // An invalid scoped proxy arrangement - let's ignore it. if (logger.isDebugEnabled()) { - logger.debug( - "Could not resolve target bean for scoped proxy '" - + beanName + "'", - ex); + logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex); } } } @@ -117,9 +110,7 @@ public class TaskListenerExecutorObjectFactory } catch (RuntimeException ex) { throw new BeanInitializationException( - "Failed to process @BeforeTask " - + "annotation on bean with name '" + beanName - + "'", + "Failed to process @BeforeTask " + "annotation on bean with name '" + beanName + "'", ex); } } @@ -130,12 +121,11 @@ public class TaskListenerExecutorObjectFactory private void processBean(String beanName, final Class type) { if (!this.nonAnnotatedClasses.contains(type)) { - Map beforeTaskMethods = (new MethodGetter()) - .getMethods(type, BeforeTask.class); - Map afterTaskMethods = (new MethodGetter()) - .getMethods(type, AfterTask.class); - Map failedTaskMethods = (new MethodGetter()) - .getMethods(type, FailedTask.class); + Map beforeTaskMethods = (new MethodGetter()).getMethods(type, + BeforeTask.class); + Map afterTaskMethods = (new MethodGetter()).getMethods(type, AfterTask.class); + Map failedTaskMethods = (new MethodGetter()).getMethods(type, + FailedTask.class); if (beforeTaskMethods.isEmpty() && afterTaskMethods.isEmpty()) { this.nonAnnotatedClasses.add(type); @@ -143,22 +133,19 @@ public class TaskListenerExecutorObjectFactory } if (!beforeTaskMethods.isEmpty()) { for (Method beforeTaskMethod : beforeTaskMethods.keySet()) { - this.beforeTaskInstances - .computeIfAbsent(beforeTaskMethod, k -> new LinkedHashSet<>()) + this.beforeTaskInstances.computeIfAbsent(beforeTaskMethod, k -> new LinkedHashSet<>()) .add(this.context.getBean(beanName)); } } if (!afterTaskMethods.isEmpty()) { for (Method afterTaskMethod : afterTaskMethods.keySet()) { - this.afterTaskInstances - .computeIfAbsent(afterTaskMethod, k -> new LinkedHashSet<>()) + this.afterTaskInstances.computeIfAbsent(afterTaskMethod, k -> new LinkedHashSet<>()) .add(this.context.getBean(beanName)); } } if (!failedTaskMethods.isEmpty()) { for (Method failedTaskMethod : failedTaskMethods.keySet()) { - this.failedTaskInstances - .computeIfAbsent(failedTaskMethod, k -> new LinkedHashSet<>()) + this.failedTaskInstances.computeIfAbsent(failedTaskMethod, k -> new LinkedHashSet<>()) .add(this.context.getBean(beanName)); } } @@ -167,11 +154,10 @@ public class TaskListenerExecutorObjectFactory private static class MethodGetter { - public Map getMethods(final Class type, - final Class annotationClass) { + public Map getMethods(final Class type, final Class annotationClass) { return MethodIntrospector.selectMethods(type, - (MethodIntrospector.MetadataLookup) method -> AnnotationUtils - .findAnnotation(method, annotationClass)); + (MethodIntrospector.MetadataLookup) method -> AnnotationUtils.findAnnotation(method, + annotationClass)); } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskObservations.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskObservations.java index 273d716b..ca0622b3 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskObservations.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskObservations.java @@ -51,8 +51,9 @@ public class TaskObservations { private Observation.ObservationConvention customObservationConvention; - public TaskObservations(ObservationRegistry observationRegistry, TaskObservationCloudKeyValues taskObservationCloudKeyValues, - Observation.ObservationConvention customObservationConvention) { + public TaskObservations(ObservationRegistry observationRegistry, + TaskObservationCloudKeyValues taskObservationCloudKeyValues, + Observation.ObservationConvention customObservationConvention) { this.observationRegistry = observationRegistry; this.taskObservationCloudKeyValues = taskObservationCloudKeyValues; this.customObservationConvention = customObservationConvention; @@ -68,34 +69,38 @@ public class TaskObservations { public void onTaskStartup(TaskExecution taskExecution) { - this.taskObservationContext = new TaskExecutionObservationContext(taskExecution); - Observation observation = TaskExecutionObservation.TASK_ACTIVE.observation(this.customObservationConvention, new DefaultTaskExecutionObservationConvention(), this.taskObservationContext, this.observationRegistry) - .contextualName(String.valueOf(taskExecution.getExecutionId())) - .keyValuesProvider(this.observationsProvider) - .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), getValueOrDefault(taskExecution.getTaskName())) - .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "" + taskExecution.getExecutionId()) - .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), - (getValueOrDefault(taskExecution.getParentExecutionId()))) - .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(), - (getValueOrDefault(taskExecution.getExternalExecutionId()))); + Observation observation = TaskExecutionObservation.TASK_ACTIVE + .observation(this.customObservationConvention, new DefaultTaskExecutionObservationConvention(), + this.taskObservationContext, this.observationRegistry) + .contextualName(String.valueOf(taskExecution.getExecutionId())) + .keyValuesProvider(this.observationsProvider) + .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), + getValueOrDefault(taskExecution.getTaskName())) + .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), + "" + taskExecution.getExecutionId()) + .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), + (getValueOrDefault(taskExecution.getParentExecutionId()))) + .lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(), + (getValueOrDefault(taskExecution.getExternalExecutionId()))); if (taskObservationCloudKeyValues != null) { observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(), - this.taskObservationCloudKeyValues.getOrganizationName()); + this.taskObservationCloudKeyValues.getOrganizationName()); observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(), - this.taskObservationCloudKeyValues.getSpaceId()); + this.taskObservationCloudKeyValues.getSpaceId()); observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(), - this.taskObservationCloudKeyValues.getSpaceName()); + this.taskObservationCloudKeyValues.getSpaceName()); observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(), - this.taskObservationCloudKeyValues.getApplicationId()); + this.taskObservationCloudKeyValues.getApplicationId()); observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(), - this.taskObservationCloudKeyValues.getApplicationName()); + this.taskObservationCloudKeyValues.getApplicationName()); observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(), - this.taskObservationCloudKeyValues.getApplicationVersion()); - observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), - this.taskObservationCloudKeyValues.getInstanceIndex()); + this.taskObservationCloudKeyValues.getApplicationVersion()); + observation.lowCardinalityKeyValue( + TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), + this.taskObservationCloudKeyValues.getInstanceIndex()); } observation.start(); @@ -107,8 +112,8 @@ public class TaskObservations { } public void onTaskFailed(Throwable throwable) { - this.taskObservationContext.setStatus(STATUS_FAILURE); - this.scope.getCurrentObservation().error(throwable); + this.taskObservationContext.setStatus(STATUS_FAILURE); + this.scope.getCurrentObservation().error(throwable); } public void onTaskEnd(TaskExecution taskExecution) { @@ -118,4 +123,5 @@ public class TaskObservations { this.scope.getCurrentObservation().stop(); } } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/TaskListenerExecutor.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/TaskListenerExecutor.java index 3d0da216..66fe07ef 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/TaskListenerExecutor.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/TaskListenerExecutor.java @@ -42,8 +42,7 @@ public class TaskListenerExecutor implements TaskExecutionListener { private Map> failedTaskInstances; public TaskListenerExecutor(Map> beforeTaskInstances, - Map> afterTaskInstances, - Map> failedTaskInstances) { + Map> afterTaskInstances, Map> failedTaskInstances) { this.beforeTaskInstances = beforeTaskInstances; this.afterTaskInstances = afterTaskInstances; @@ -56,8 +55,7 @@ public class TaskListenerExecutor implements TaskExecutionListener { */ @Override public void onTaskStartup(TaskExecution taskExecution) { - executeTaskListener(taskExecution, this.beforeTaskInstances.keySet(), - this.beforeTaskInstances); + executeTaskListener(taskExecution, this.beforeTaskInstances.keySet(), this.beforeTaskInstances); } /** @@ -66,8 +64,7 @@ public class TaskListenerExecutor implements TaskExecutionListener { */ @Override public void onTaskEnd(TaskExecution taskExecution) { - executeTaskListener(taskExecution, this.afterTaskInstances.keySet(), - this.afterTaskInstances); + executeTaskListener(taskExecution, this.afterTaskInstances.keySet(), this.afterTaskInstances); } /** @@ -77,8 +74,8 @@ public class TaskListenerExecutor implements TaskExecutionListener { */ @Override public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { - executeTaskListenerWithThrowable(taskExecution, throwable, - this.failedTaskInstances.keySet(), this.failedTaskInstances); + executeTaskListenerWithThrowable(taskExecution, throwable, this.failedTaskInstances.keySet(), + this.failedTaskInstances); } private void executeTaskListener(TaskExecution taskExecution, Set methods, @@ -89,27 +86,24 @@ public class TaskListenerExecutor implements TaskExecutionListener { method.invoke(instance, taskExecution); } catch (IllegalAccessException e) { - throw new TaskExecutionException( - "@BeforeTask and @AfterTask annotated methods must be public.", - e); + throw new TaskExecutionException("@BeforeTask and @AfterTask annotated methods must be public.", e); } catch (InvocationTargetException e) { - throw new TaskExecutionException(String.format( - "Failed to process @BeforeTask or @AfterTask" - + " annotation because: %s", - e.getTargetException().getMessage()), e); + throw new TaskExecutionException( + String.format("Failed to process @BeforeTask or @AfterTask" + " annotation because: %s", + e.getTargetException().getMessage()), + e); } catch (IllegalArgumentException e) { - throw new TaskExecutionException("taskExecution parameter " - + "is required for @BeforeTask and @AfterTask annotated methods", + throw new TaskExecutionException( + "taskExecution parameter " + "is required for @BeforeTask and @AfterTask annotated methods", e); } } } } - private void executeTaskListenerWithThrowable(TaskExecution taskExecution, - Throwable throwable, Set methods, + private void executeTaskListenerWithThrowable(TaskExecution taskExecution, Throwable throwable, Set methods, Map> instances) { for (Method method : methods) { for (Object instance : instances.get(method)) { @@ -117,19 +111,17 @@ public class TaskListenerExecutor implements TaskExecutionListener { method.invoke(instance, taskExecution, throwable); } catch (IllegalAccessException e) { - throw new TaskExecutionException( - "@FailedTask annotated methods must be public.", e); + throw new TaskExecutionException("@FailedTask annotated methods must be public.", e); } catch (InvocationTargetException e) { - throw new TaskExecutionException(String.format( - "Failed to process @FailedTask " + "annotation because: %s", - e.getTargetException().getMessage()), e); + throw new TaskExecutionException( + String.format("Failed to process @FailedTask " + "annotation because: %s", + e.getTargetException().getMessage()), + e); } catch (IllegalArgumentException e) { - throw new TaskExecutionException( - "taskExecution and throwable parameters " - + "are required for @FailedTask annotated methods", - e); + throw new TaskExecutionException("taskExecution and throwable parameters " + + "are required for @FailedTask annotated methods", e); } } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExecution.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExecution.java index e9de3dbf..4d70e11b 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExecution.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExecution.java @@ -90,9 +90,9 @@ public class TaskExecution { this.arguments = new ArrayList<>(); } - public TaskExecution(long executionId, Integer exitCode, String taskName, - Date startTime, Date endTime, String exitMessage, List arguments, - String errorMessage, String externalExecutionId, Long parentExecutionId) { + public TaskExecution(long executionId, Integer exitCode, String taskName, Date startTime, Date endTime, + String exitMessage, List arguments, String errorMessage, String externalExecutionId, + Long parentExecutionId) { Assert.notNull(arguments, "arguments must not be null"); this.executionId = executionId; @@ -107,12 +107,11 @@ public class TaskExecution { this.parentExecutionId = parentExecutionId; } - public TaskExecution(long executionId, Integer exitCode, String taskName, - Date startTime, Date endTime, String exitMessage, List arguments, - String errorMessage, String externalExecutionId) { + public TaskExecution(long executionId, Integer exitCode, String taskName, Date startTime, Date endTime, + String exitMessage, List arguments, String errorMessage, String externalExecutionId) { - this(executionId, exitCode, taskName, startTime, endTime, exitMessage, arguments, - errorMessage, externalExecutionId, null); + this(executionId, exitCode, taskName, startTime, endTime, exitMessage, arguments, errorMessage, + externalExecutionId, null); } public long getExecutionId() { @@ -193,12 +192,10 @@ public class TaskExecution { @Override public String toString() { - return "TaskExecution{" + "executionId=" + this.executionId - + ", parentExecutionId=" + this.parentExecutionId + ", exitCode=" - + this.exitCode + ", taskName='" + this.taskName + '\'' + ", startTime=" - + this.startTime + ", endTime=" + this.endTime + ", exitMessage='" - + this.exitMessage + '\'' + ", externalExecutionId='" - + this.externalExecutionId + '\'' + ", errorMessage='" + this.errorMessage + return "TaskExecution{" + "executionId=" + this.executionId + ", parentExecutionId=" + this.parentExecutionId + + ", exitCode=" + this.exitCode + ", taskName='" + this.taskName + '\'' + ", startTime=" + + this.startTime + ", endTime=" + this.endTime + ", exitMessage='" + this.exitMessage + '\'' + + ", externalExecutionId='" + this.externalExecutionId + '\'' + ", errorMessage='" + this.errorMessage + '\'' + ", arguments=" + this.arguments + '}'; } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskRepository.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskRepository.java index 389efa3c..505e3156 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskRepository.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskRepository.java @@ -39,8 +39,7 @@ public interface TaskRepository { * @return the updated {@link TaskExecution} */ @Transactional("springCloudTaskTransactionManager") - TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage); + TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage); /** * Notifies the repository that a taskExecution has completed. @@ -53,8 +52,8 @@ public interface TaskRepository { * @since 1.1.0 */ @Transactional("springCloudTaskTransactionManager") - TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage, String errorMessage); + TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage, + String errorMessage); /** * Notifies the repository that a taskExecution needs to be created. @@ -99,8 +98,8 @@ public interface TaskRepository { * @return TaskExecution created based on the parameters. */ @Transactional("springCloudTaskTransactionManager") - TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, - List arguments, String externalExecutionId); + TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List arguments, + String externalExecutionId); /** * Notifies the repository to update the taskExecution's externalExecutionId. @@ -122,7 +121,7 @@ public interface TaskRepository { * a TaskExecution. */ @Transactional("springCloudTaskTransactionManager") - TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, - List arguments, String externalExecutionId, Long parentExecutionId); + TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java index ef0e815f..c46fdbf5 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java @@ -66,10 +66,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { /** * SELECT clause for task execution. */ - public static final String SELECT_CLAUSE = "TASK_EXECUTION_ID, " - + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, " - + "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, " - + "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID "; + public static final String SELECT_CLAUSE = "TASK_EXECUTION_ID, " + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, " + + "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, " + "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID "; /** * FROM clause for task execution. @@ -116,15 +114,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { private static final String GET_EXECUTION_BY_ID = "SELECT TASK_EXECUTION_ID, " + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, " - + "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, " - + "PARENT_EXECUTION_ID " + + "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, " + "PARENT_EXECUTION_ID " + "from %PREFIX%EXECUTION where TASK_EXECUTION_ID = :taskExecutionId"; private static final String FIND_ARGUMENT_FROM_ID = "SELECT TASK_EXECUTION_ID, " + "TASK_PARAM from %PREFIX%EXECUTION_PARAMS where TASK_EXECUTION_ID = :taskExecutionId"; - private static final String TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM " - + "%PREFIX%EXECUTION "; + private static final String TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM " + "%PREFIX%EXECUTION "; private static final String TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM " + "%PREFIX%EXECUTION where TASK_NAME = :taskName"; @@ -138,8 +134,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { private static final String LAST_TASK_EXECUTIONS_BY_TASK_NAMES = "select TE2.* from (" + "select MAX(TE.TASK_EXECUTION_ID) as TASK_EXECUTION_ID, TE.TASK_NAME, TE.START_TIME from (" + "select TASK_NAME, MAX(START_TIME) as START_TIME" - + " FROM %PREFIX%EXECUTION where TASK_NAME in (:taskNames)" - + " GROUP BY TASK_NAME" + ") TE_MAX " + + " FROM %PREFIX%EXECUTION where TASK_NAME in (:taskNames)" + " GROUP BY TASK_NAME" + ") TE_MAX " + "inner join %PREFIX%EXECUTION TE ON TE.TASK_NAME = TE_MAX.TASK_NAME AND TE.START_TIME = TE_MAX.START_TIME " + "group by TE.TASK_NAME, TE.START_TIME" + ") TE1 " + "inner join %PREFIX%EXECUTION TE2 ON TE1.TASK_EXECUTION_ID = TE2.TASK_EXECUTION_ID " @@ -152,6 +147,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { private static final String FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID = "SELECT JOB_EXECUTION_ID " + "FROM %PREFIX%TASK_BATCH WHERE TASK_EXECUTION_ID = :taskExecutionId"; + private static final Set validSortColumns = new HashSet<>(10); static { @@ -168,9 +164,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } private final NamedParameterJdbcTemplate jdbcTemplate; + private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX; + private DataSource dataSource; + private LinkedHashMap orderMap; + private DataFieldMaxValueIncrementer taskIncrementer; /** @@ -199,25 +199,22 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId) { - return createTaskExecution(taskName, startTime, arguments, externalExecutionId, - null); + public TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId) { + return createTaskExecution(taskName, startTime, arguments, externalExecutionId, null); } @Override - public TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId, Long parentExecutionId) { + public TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId) { long nextExecutionId = getNextExecutionId(); - TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName, - startTime, null, null, arguments, null, externalExecutionId); + TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName, startTime, null, null, + arguments, null, externalExecutionId); final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", nextExecutionId, Types.BIGINT) - .addValue("exitCode", null, Types.INTEGER) - .addValue("startTime", startTime, Types.TIMESTAMP) - .addValue("taskName", taskName, Types.VARCHAR) + .addValue("taskExecutionId", nextExecutionId, Types.BIGINT).addValue("exitCode", null, Types.INTEGER) + .addValue("startTime", startTime, Types.TIMESTAMP).addValue("taskName", taskName, Types.VARCHAR) .addValue("lastUpdated", new Date(), Types.TIMESTAMP) .addValue("externalExecutionId", externalExecutionId, Types.VARCHAR) .addValue("parentExecutionId", parentExecutionId, Types.BIGINT); @@ -228,25 +225,20 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public TaskExecution startTaskExecution(long executionId, String taskName, - Date startTime, List arguments, String externalExecutionId) { - return startTaskExecution(executionId, taskName, startTime, arguments, - externalExecutionId, null); + public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionId) { + return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionId, null); } @Override - public TaskExecution startTaskExecution(long executionId, String taskName, - Date startTime, List arguments, String externalExecutionId, - Long parentExecutionId) { - TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, - startTime, null, null, arguments, null, externalExecutionId, - parentExecutionId); + public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId) { + TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, startTime, null, null, arguments, + null, externalExecutionId, parentExecutionId); final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("startTime", startTime, Types.TIMESTAMP) - .addValue("exitCode", null, Types.INTEGER) - .addValue("taskName", taskName, Types.VARCHAR) - .addValue("lastUpdated", new Date(), Types.TIMESTAMP) + .addValue("startTime", startTime, Types.TIMESTAMP).addValue("exitCode", null, Types.INTEGER) + .addValue("taskName", taskName, Types.VARCHAR).addValue("lastUpdated", new Date(), Types.TIMESTAMP) .addValue("parentExecutionId", parentExecutionId, Types.BIGINT) .addValue("taskExecutionId", executionId, Types.BIGINT); @@ -257,8 +249,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } else { updateString += START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX; - queryParameters.addValue("externalExecutionId", externalExecutionId, - Types.VARCHAR); + queryParameters.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR); } this.jdbcTemplate.update(getQuery(updateString), queryParameters); @@ -267,22 +258,20 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public void completeTaskExecution(long taskExecutionId, Integer exitCode, - Date endTime, String exitMessage, String errorMessage) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); + public void completeTaskExecution(long taskExecutionId, Integer exitCode, Date endTime, String exitMessage, + String errorMessage) { + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId", + taskExecutionId, Types.BIGINT); // Check if given TaskExecution's Id already exists, if none is found // it is invalid and an exception should be thrown. - if (this.jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS), - queryParameters, Integer.class) != 1) { - throw new IllegalStateException( - "Invalid TaskExecution, ID " + taskExecutionId + " not found."); + if (this.jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS), queryParameters, + Integer.class) != 1) { + throw new IllegalStateException("Invalid TaskExecution, ID " + taskExecutionId + " not found."); } final MapSqlParameterSource parameters = new MapSqlParameterSource() - .addValue("endTime", endTime, Types.TIMESTAMP) - .addValue("exitCode", exitCode, Types.INTEGER) + .addValue("endTime", endTime, Types.TIMESTAMP).addValue("exitCode", exitCode, Types.INTEGER) .addValue("exitMessage", exitMessage, Types.VARCHAR) .addValue("errorMessage", errorMessage, Types.VARCHAR) .addValue("lastUpdated", new Date(), Types.TIMESTAMP) @@ -292,20 +281,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public void completeTaskExecution(long taskExecutionId, Integer exitCode, - Date endTime, String exitMessage) { + public void completeTaskExecution(long taskExecutionId, Integer exitCode, Date endTime, String exitMessage) { completeTaskExecution(taskExecutionId, exitCode, endTime, exitMessage, null); } @Override public TaskExecution getTaskExecution(long executionId) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", executionId, Types.BIGINT); + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId", + executionId, Types.BIGINT); try { - TaskExecution taskExecution = this.jdbcTemplate.queryForObject( - getQuery(GET_EXECUTION_BY_ID), queryParameters, - new TaskExecutionRowMapper()); + TaskExecution taskExecution = this.jdbcTemplate.queryForObject(getQuery(GET_EXECUTION_BY_ID), + queryParameters, new TaskExecutionRowMapper()); taskExecution.setArguments(getTaskArguments(executionId)); return taskExecution; } @@ -317,12 +304,12 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public long getTaskExecutionCountByTaskName(String taskName) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskName", taskName, Types.VARCHAR); + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskName", taskName, + Types.VARCHAR); try { - return this.jdbcTemplate.queryForObject( - getQuery(TASK_EXECUTION_COUNT_BY_NAME), queryParameters, Long.class); + return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT_BY_NAME), queryParameters, + Long.class); } catch (EmptyResultDataAccessException e) { return 0; @@ -331,12 +318,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public long getRunningTaskExecutionCountByTaskName(String taskName) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskName", taskName, Types.VARCHAR); + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskName", taskName, + Types.VARCHAR); try { - return this.jdbcTemplate.queryForObject( - getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters, + return this.jdbcTemplate.queryForObject(getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters, Long.class); } catch (EmptyResultDataAccessException e) { @@ -349,8 +335,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { try { final MapSqlParameterSource queryParameters = new MapSqlParameterSource(); - return this.jdbcTemplate.queryForObject( - getQuery(RUNNING_TASK_EXECUTION_COUNT), queryParameters, Long.class); + return this.jdbcTemplate.queryForObject(getQuery(RUNNING_TASK_EXECUTION_COUNT), queryParameters, + Long.class); } catch (EmptyResultDataAccessException e) { return 0; @@ -369,15 +355,14 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } } - Assert.isTrue(taskNamesAsList.size() == taskNames.length, String.format( - "Task names must not contain any empty elements but %s of %s were empty or null.", - taskNames.length - taskNamesAsList.size(), taskNames.length)); + Assert.isTrue(taskNamesAsList.size() == taskNames.length, + String.format("Task names must not contain any empty elements but %s of %s were empty or null.", + taskNames.length - taskNamesAsList.size(), taskNames.length)); try { - final Map> paramMap = Collections - .singletonMap("taskNames", taskNamesAsList); - return this.jdbcTemplate.query(getQuery(LAST_TASK_EXECUTIONS_BY_TASK_NAMES), - paramMap, new TaskExecutionRowMapper()); + final Map> paramMap = Collections.singletonMap("taskNames", taskNamesAsList); + return this.jdbcTemplate.query(getQuery(LAST_TASK_EXECUTIONS_BY_TASK_NAMES), paramMap, + new TaskExecutionRowMapper()); } catch (EmptyResultDataAccessException e) { return Collections.emptyList(); @@ -387,8 +372,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public TaskExecution getLatestTaskExecutionForTaskName(String taskName) { Assert.hasText(taskName, "The task name must not be empty."); - final List taskExecutions = this - .getLatestTaskExecutionsByTaskNames(taskName); + final List taskExecutions = this.getLatestTaskExecutionsByTaskNames(taskName); if (taskExecutions.isEmpty()) { return null; } @@ -397,8 +381,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } else { throw new IllegalStateException( - "Only expected a single TaskExecution but received " - + taskExecutions.size()); + "Only expected a single TaskExecution but received " + taskExecutions.size()); } } @@ -406,8 +389,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { public long getTaskExecutionCount() { try { - return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT), - new MapSqlParameterSource(), Long.class); + return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT), new MapSqlParameterSource(), + Long.class); } catch (EmptyResultDataAccessException e) { return 0; @@ -415,32 +398,26 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public Page findRunningTaskExecutions(String taskName, - Pageable pageable) { - return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, - RUNNING_TASK_WHERE_CLAUSE, - new MapSqlParameterSource("taskName", taskName), - getRunningTaskExecutionCountByTaskName(taskName)); + public Page findRunningTaskExecutions(String taskName, Pageable pageable) { + return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, RUNNING_TASK_WHERE_CLAUSE, + new MapSqlParameterSource("taskName", taskName), getRunningTaskExecutionCountByTaskName(taskName)); } @Override - public Page findTaskExecutionsByName(String taskName, - Pageable pageable) { - return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, - TASK_NAME_WHERE_CLAUSE, new MapSqlParameterSource("taskName", taskName), - getTaskExecutionCountByTaskName(taskName)); + public Page findTaskExecutionsByName(String taskName, Pageable pageable) { + return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, TASK_NAME_WHERE_CLAUSE, + new MapSqlParameterSource("taskName", taskName), getTaskExecutionCountByTaskName(taskName)); } @Override public List getTaskNames() { - return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES), - new MapSqlParameterSource(), String.class); + return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES), new MapSqlParameterSource(), String.class); } @Override public Page findAll(Pageable pageable) { - return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, null, - new MapSqlParameterSource(), getTaskExecutionCount()); + return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, null, new MapSqlParameterSource(), + getTaskExecutionCount()); } public void setTaskIncrementer(DataFieldMaxValueIncrementer taskIncrementer) { @@ -453,12 +430,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public Long getTaskExecutionIdByJobExecutionId(long jobExecutionId) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("jobExecutionId", jobExecutionId, Types.BIGINT); + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("jobExecutionId", + jobExecutionId, Types.BIGINT); try { - return this.jdbcTemplate.queryForObject( - getQuery(FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID), queryParameters, + return this.jdbcTemplate.queryForObject(getQuery(FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID), queryParameters, Long.class); } catch (EmptyResultDataAccessException e) { @@ -468,21 +444,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId) { - final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); + final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId", + taskExecutionId, Types.BIGINT); try { - return this.jdbcTemplate.query( - getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID), queryParameters, + return this.jdbcTemplate.query(getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID), queryParameters, new ResultSetExtractor>() { @Override - public Set extractData(ResultSet resultSet) - throws SQLException, DataAccessException { + public Set extractData(ResultSet resultSet) throws SQLException, DataAccessException { Set jobExecutionIds = new TreeSet<>(); while (resultSet.next()) { - jobExecutionIds - .add(resultSet.getLong("JOB_EXECUTION_ID")); + jobExecutionIds.add(resultSet.getLong("JOB_EXECUTION_ID")); } return jobExecutionIds; @@ -495,23 +468,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public void updateExternalExecutionId(long taskExecutionId, - String externalExecutionId) { + public void updateExternalExecutionId(long taskExecutionId, String externalExecutionId) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() .addValue("externalExecutionId", externalExecutionId, Types.VARCHAR) .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); - if (this.jdbcTemplate.update( - getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID), - queryParameters) != 1) { - throw new IllegalStateException( - "Invalid TaskExecution, ID " + taskExecutionId + " not found."); + if (this.jdbcTemplate.update(getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID), queryParameters) != 1) { + throw new IllegalStateException("Invalid TaskExecution, ID " + taskExecutionId + " not found."); } } - private Page queryForPageableResults(Pageable pageable, - String selectClause, String fromClause, String whereClause, - MapSqlParameterSource queryParameters, long totalCount) { + private Page queryForPageableResults(Pageable pageable, String selectClause, String fromClause, + String whereClause, MapSqlParameterSource queryParameters, long totalCount) { SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean(); factoryBean.setSelectClause(selectClause); factoryBean.setFromClause(fromClause); @@ -551,8 +519,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { throw new IllegalStateException(e); } String query = pagingQueryProvider.getPageQuery(pageable); - List resultList = this.jdbcTemplate.query(getQuery(query), - queryParameters, new TaskExecutionRowMapper()); + List resultList = this.jdbcTemplate.query(getQuery(query), queryParameters, + new TaskExecutionRowMapper()); return new PageImpl<>(resultList, pageable, totalCount); } @@ -572,8 +540,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } /** - * Convenience method that inserts an individual records into the TASK_EXECUTION_PARAMS - * table. + * Convenience method that inserts an individual records into the + * TASK_EXECUTION_PARAMS table. * @param taskExecutionId id of a task execution * @param taskParam task parameters */ @@ -613,11 +581,10 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { if (rs.wasNull()) { parentExecutionId = null; } - return new TaskExecution(id, getNullableExitCode(rs), - rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"), - rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"), - getTaskArguments(id), rs.getString("ERROR_MESSAGE"), - rs.getString("EXTERNAL_EXECUTION_ID"), parentExecutionId); + return new TaskExecution(id, getNullableExitCode(rs), rs.getString("TASK_NAME"), + rs.getTimestamp("START_TIME"), rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"), + getTaskArguments(id), rs.getString("ERROR_MESSAGE"), rs.getString("EXTERNAL_EXECUTION_ID"), + parentExecutionId); } private Integer getNullableExitCode(ResultSet rs) throws SQLException { diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDao.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDao.java index dee6163f..0b7cd198 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDao.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDao.java @@ -58,34 +58,30 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId) { - return createTaskExecution(taskName, startTime, arguments, externalExecutionId, - null); + public TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId) { + return createTaskExecution(taskName, startTime, arguments, externalExecutionId, null); } @Override - public TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId, Long parentExecutionId) { + public TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId) { long taskExecutionId = getNextExecutionId(); - TaskExecution taskExecution = new TaskExecution(taskExecutionId, null, taskName, - startTime, null, null, arguments, null, externalExecutionId, - parentExecutionId); + TaskExecution taskExecution = new TaskExecution(taskExecutionId, null, taskName, startTime, null, null, + arguments, null, externalExecutionId, parentExecutionId); this.taskExecutions.put(taskExecutionId, taskExecution); return taskExecution; } @Override - public TaskExecution startTaskExecution(long executionId, String taskName, - Date startTime, List arguments, String externalExecutionid) { - return startTaskExecution(executionId, taskName, startTime, arguments, - externalExecutionid, null); + public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionid) { + return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionid, null); } @Override - public TaskExecution startTaskExecution(long executionId, String taskName, - Date startTime, List arguments, String externalExecutionid, - Long parentExecutionId) { + public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionid, Long parentExecutionId) { TaskExecution taskExecution = this.taskExecutions.get(executionId); taskExecution.setTaskName(taskName); taskExecution.setStartTime(startTime); @@ -98,11 +94,10 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage, String errorMessage) { + public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage, + String errorMessage) { if (!this.taskExecutions.containsKey(executionId)) { - throw new IllegalStateException( - "Invalid TaskExecution, ID " + executionId + " not found."); + throw new IllegalStateException("Invalid TaskExecution, ID " + executionId + " not found."); } TaskExecution taskExecution = this.taskExecutions.get(executionId); @@ -113,8 +108,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage) { + public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) { completeTaskExecution(executionId, exitCode, endTime, exitMessage, null); } @@ -138,8 +132,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { public long getRunningTaskExecutionCountByTaskName(String taskName) { int count = 0; for (Map.Entry entry : this.taskExecutions.entrySet()) { - if (entry.getValue().getTaskName().equals(taskName) - && entry.getValue().getEndTime() == null) { + if (entry.getValue().getTaskName().equals(taskName) && entry.getValue().getEndTime() == null) { count++; } } @@ -163,30 +156,25 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public Page findRunningTaskExecutions(String taskName, - Pageable pageable) { + public Page findRunningTaskExecutions(String taskName, Pageable pageable) { Set result = getTaskExecutionTreeSet(); for (Map.Entry entry : this.taskExecutions.entrySet()) { - if (entry.getValue().getTaskName().equals(taskName) - && entry.getValue().getEndTime() == null) { + if (entry.getValue().getTaskName().equals(taskName) && entry.getValue().getEndTime() == null) { result.add(entry.getValue()); } } - return getPageFromList(new ArrayList<>(result), pageable, - getRunningTaskExecutionCountByTaskName(taskName)); + return getPageFromList(new ArrayList<>(result), pageable, getRunningTaskExecutionCountByTaskName(taskName)); } @Override - public Page findTaskExecutionsByName(String taskName, - Pageable pageable) { + public Page findTaskExecutionsByName(String taskName, Pageable pageable) { Set filteredSet = getTaskExecutionTreeSet(); for (Map.Entry entry : this.taskExecutions.entrySet()) { if (entry.getValue().getTaskName().equals(taskName)) { filteredSet.add(entry.getValue()); } } - return getPageFromList(new ArrayList<>(filteredSet), pageable, - getTaskExecutionCountByTaskName(taskName)); + return getPageFromList(new ArrayList<>(filteredSet), pageable, getTaskExecutionCountByTaskName(taskName)); } @Override @@ -220,8 +208,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { found: - for (Map.Entry> association : this.batchJobAssociations - .entrySet()) { + for (Map.Entry> association : this.batchJobAssociations.entrySet()) { for (Long curJobExecutionId : association.getValue()) { if (curJobExecutionId.equals(jobExecutionId)) { taskId = association.getKey(); @@ -236,8 +223,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId) { if (this.batchJobAssociations.containsKey(taskExecutionId)) { - return Collections - .unmodifiableSet(this.batchJobAssociations.get(taskExecutionId)); + return Collections.unmodifiableSet(this.batchJobAssociations.get(taskExecutionId)); } else { return new TreeSet<>(); @@ -245,11 +231,9 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public void updateExternalExecutionId(long taskExecutionId, - String externalExecutionId) { + public void updateExternalExecutionId(long taskExecutionId, String externalExecutionId) { TaskExecution taskExecution = this.taskExecutions.get(taskExecutionId); - Assert.notNull(taskExecution, - "Invalid TaskExecution, ID " + taskExecutionId + " not found."); + Assert.notNull(taskExecution, "Invalid TaskExecution, ID " + taskExecutionId + " not found."); taskExecution.setExternalExecutionId(externalExecutionId); } @@ -263,22 +247,17 @@ public class MapTaskExecutionDao implements TaskExecutionDao { public int compare(TaskExecution e1, TaskExecution e2) { int result = e1.getStartTime().compareTo(e2.getStartTime()); if (result == 0) { - result = Long.valueOf(e1.getExecutionId()) - .compareTo(e2.getExecutionId()); + result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId()); } return result; } }); } - private Page getPageFromList(List executionList, Pageable pageable, - long maxSize) { - long toIndex = (pageable.getOffset() + pageable.getPageSize() > executionList - .size()) ? executionList.size() - : pageable.getOffset() + pageable.getPageSize(); - return new PageImpl<>( - executionList.subList((int) pageable.getOffset(), (int) toIndex), - pageable, maxSize); + private Page getPageFromList(List executionList, Pageable pageable, long maxSize) { + long toIndex = (pageable.getOffset() + pageable.getPageSize() > executionList.size()) ? executionList.size() + : pageable.getOffset() + pageable.getPageSize(); + return new PageImpl<>(executionList.subList((int) pageable.getOffset(), (int) toIndex), pageable, maxSize); } @Override @@ -294,34 +273,29 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } } - Assert.isTrue(taskNamesAsList.size() == taskNames.length, String.format( - "Task names must not contain any empty elements but %s of %s were empty or null.", - taskNames.length - taskNamesAsList.size(), taskNames.length)); + Assert.isTrue(taskNamesAsList.size() == taskNames.length, + String.format("Task names must not contain any empty elements but %s of %s were empty or null.", + taskNames.length - taskNamesAsList.size(), taskNames.length)); final Map tempTaskExecutions = new HashMap<>(); - for (Map.Entry taskExecutionMapEntry : this.taskExecutions - .entrySet()) { - if (!taskNamesAsList - .contains(taskExecutionMapEntry.getValue().getTaskName())) { + for (Map.Entry taskExecutionMapEntry : this.taskExecutions.entrySet()) { + if (!taskNamesAsList.contains(taskExecutionMapEntry.getValue().getTaskName())) { continue; } final TaskExecution tempTaskExecution = tempTaskExecutions .get(taskExecutionMapEntry.getValue().getTaskName()); if (tempTaskExecution == null - || tempTaskExecution.getStartTime() - .before(taskExecutionMapEntry.getValue().getStartTime()) - || (tempTaskExecution.getStartTime() - .equals(taskExecutionMapEntry.getValue().getStartTime()) - && tempTaskExecution.getExecutionId() < taskExecutionMapEntry - .getValue().getExecutionId())) { + || tempTaskExecution.getStartTime().before(taskExecutionMapEntry.getValue().getStartTime()) + || (tempTaskExecution.getStartTime().equals(taskExecutionMapEntry.getValue().getStartTime()) + && tempTaskExecution.getExecutionId() < taskExecutionMapEntry.getValue() + .getExecutionId())) { tempTaskExecutions.put(taskExecutionMapEntry.getValue().getTaskName(), taskExecutionMapEntry.getValue()); } } - final List latestTaskExecutions = new ArrayList<>( - tempTaskExecutions.values()); + final List latestTaskExecutions = new ArrayList<>(tempTaskExecutions.values()); Collections.sort(latestTaskExecutions, new TaskExecutionComparator()); return latestTaskExecutions; } @@ -329,8 +303,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public TaskExecution getLatestTaskExecutionForTaskName(String taskName) { Assert.hasText(taskName, "The task name must not be empty."); - final List taskExecutions = this - .getLatestTaskExecutionsByTaskNames(taskName); + final List taskExecutions = this.getLatestTaskExecutionsByTaskNames(taskName); if (taskExecutions.isEmpty()) { return null; } @@ -339,25 +312,19 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } else { throw new IllegalStateException( - "Only expected a single TaskExecution but received " - + taskExecutions.size()); + "Only expected a single TaskExecution but received " + taskExecutions.size()); } } - private static class TaskExecutionComparator - implements Comparator, Serializable { + private static class TaskExecutionComparator implements Comparator, Serializable { @Override - public int compare(TaskExecution firstTaskExecution, - TaskExecution secondTaskExecution) { - if (firstTaskExecution.getStartTime() - .equals(secondTaskExecution.getStartTime())) { - return Long.compare(firstTaskExecution.getExecutionId(), - secondTaskExecution.getExecutionId()); + public int compare(TaskExecution firstTaskExecution, TaskExecution secondTaskExecution) { + if (firstTaskExecution.getStartTime().equals(secondTaskExecution.getStartTime())) { + return Long.compare(firstTaskExecution.getExecutionId(), secondTaskExecution.getExecutionId()); } else { - return secondTaskExecution.getStartTime() - .compareTo(firstTaskExecution.getStartTime()); + return secondTaskExecution.getStartTime().compareTo(firstTaskExecution.getStartTime()); } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/TaskExecutionDao.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/TaskExecutionDao.java index 945aec73..8339c9c5 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/TaskExecutionDao.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/TaskExecutionDao.java @@ -42,8 +42,8 @@ public interface TaskExecutionDao { * @param externalExecutionId id assigned to the task by the platform * @return A fully qualified {@link TaskExecution} instance. */ - TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId); + TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId); /** * Save a new {@link TaskExecution}. @@ -55,8 +55,8 @@ public interface TaskExecutionDao { * @return A fully qualified {@link TaskExecution} instance. * @since 1.2.0 */ - TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId, Long parentExecutionId); + TaskExecution createTaskExecution(String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId); /** * Update and existing {@link TaskExecution} to mark it as started. @@ -69,8 +69,8 @@ public interface TaskExecutionDao { * start. * @since 1.1.0 */ - TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, - List arguments, String externalExecutionId); + TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionId); /** * Update and existing {@link TaskExecution} to mark it as started. @@ -84,8 +84,8 @@ public interface TaskExecutionDao { * start. * @since 1.2.0 */ - TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, - List arguments, String externalExecutionId, Long parentExecutionId); + TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId); /** * Update and existing {@link TaskExecution} to mark it as completed. @@ -96,8 +96,8 @@ public interface TaskExecutionDao { * @param errorMessage error information available upon failure of a task. * @since 1.1.0 */ - void completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage, String errorMessage); + void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage, + String errorMessage); /** * Update and existing {@link TaskExecution}. @@ -106,8 +106,7 @@ public interface TaskExecutionDao { * @param endTime the time the task completed. * @param exitMessage the message assigned to the task upon completion. */ - void completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage); + void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage); /** * Retrieves a task execution from the task repository. diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/AbstractSqlPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/AbstractSqlPagingQueryProvider.java index 32c1d3ae..2daa6c60 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/AbstractSqlPagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/AbstractSqlPagingQueryProvider.java @@ -144,13 +144,11 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi sql.append(" WHERE ").append(this.whereClause); } List namedParameters = new ArrayList<>(); - this.parameterCount = JdbcParameterUtils - .countParameterPlaceholders(sql.toString(), namedParameters); + this.parameterCount = JdbcParameterUtils.countParameterPlaceholders(sql.toString(), namedParameters); if (namedParameters.size() > 0) { if (this.parameterCount != namedParameters.size()) { throw new InvalidDataAccessApiUsageException( - "You can't use both named parameters and classic \"?\" placeholders: " - + sql); + "You can't use both named parameters and classic \"?\" placeholders: " + sql); } this.usingNamedParameters = true; } @@ -159,8 +157,7 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi private String removeKeyWord(String keyWord, String clause) { String temp = clause.trim(); String keyWordString = keyWord + " "; - if (temp.toLowerCase().startsWith(keyWordString) - && temp.length() > keyWordString.length()) { + if (temp.toLowerCase().startsWith(keyWordString) && temp.length() > keyWordString.length()) { return temp.substring(keyWordString.length()); } else { diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/Db2PagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/Db2PagingQueryProvider.java index 66424c18..d97b7175 100755 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/Db2PagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/Db2PagingQueryProvider.java @@ -32,17 +32,15 @@ public class Db2PagingQueryProvider extends AbstractSqlPagingQueryProvider { public String getPageQuery(Pageable pageable) { long offset = pageable.getOffset() + 1; return generateRowNumSqlQueryWithNesting(getSelectClause(), false, - "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize())); + "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize())); } - private String generateRowNumSqlQueryWithNesting(String selectClause, - boolean remainingPageQuery, String rowNumClause) { + private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery, + String rowNumClause) { StringBuilder sql = new StringBuilder(); - sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ") - .append(selectClause).append(", ") + sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ") .append("ROW_NUMBER() OVER() as TMP_ROW_NUM"); - sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ") - .append(this.getFromClause()); + sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ").append(this.getFromClause()); SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)); sql.append(")) WHERE ").append(rowNumClause); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProvider.java index 4428818b..4b2d2b98 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProvider.java @@ -29,10 +29,8 @@ public class H2PagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override public String getPageQuery(Pageable pageable) { - String limitClause = new StringBuilder().append("OFFSET ") - .append(pageable.getOffset()).append(" ROWS FETCH NEXT ") - .append(pageable.getPageSize()).append(" ROWS ONLY") - .toString(); + String limitClause = new StringBuilder().append("OFFSET ").append(pageable.getOffset()) + .append(" ROWS FETCH NEXT ").append(pageable.getPageSize()).append(" ROWS ONLY").toString(); return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/HsqlPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/HsqlPagingQueryProvider.java index 71eb2618..82ff4119 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/HsqlPagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/HsqlPagingQueryProvider.java @@ -29,9 +29,8 @@ public class HsqlPagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override public String getPageQuery(Pageable pageable) { - String topClause = new StringBuilder().append("LIMIT ") - .append(pageable.getOffset()).append(" ").append(pageable.getPageSize()) - .toString(); + String topClause = new StringBuilder().append("LIMIT ").append(pageable.getOffset()).append(" ") + .append(pageable.getPageSize()).toString(); return SqlPagingQueryUtils.generateTopJumpToQuery(this, topClause); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/MySqlPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/MySqlPagingQueryProvider.java index e9647e6a..65dfa84a 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/MySqlPagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/MySqlPagingQueryProvider.java @@ -28,9 +28,8 @@ public class MySqlPagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override public String getPageQuery(Pageable pageable) { - String topClause = new StringBuilder().append("LIMIT ") - .append(pageable.getOffset()).append(", ").append(pageable.getPageSize()) - .toString(); + String topClause = new StringBuilder().append("LIMIT ").append(pageable.getOffset()).append(", ") + .append(pageable.getPageSize()).toString(); return SqlPagingQueryUtils.generateLimitJumpToQuery(this, topClause); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/OraclePagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/OraclePagingQueryProvider.java index 85a45269..73b3c306 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/OraclePagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/OraclePagingQueryProvider.java @@ -31,17 +31,15 @@ public class OraclePagingQueryProvider extends AbstractSqlPagingQueryProvider { public String getPageQuery(Pageable pageable) { long offset = pageable.getOffset() + 1; return generateRowNumSqlQueryWithNesting(getSelectClause(), false, - "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " - + (offset + pageable.getPageSize())); + "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize())); } - private String generateRowNumSqlQueryWithNesting(String selectClause, - boolean remainingPageQuery, String rowNumClause) { + private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery, + String rowNumClause) { StringBuilder sql = new StringBuilder(); - sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ") - .append(selectClause).append(", ").append("ROWNUM as TMP_ROW_NUM"); - sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ") - .append(this.getFromClause()); + sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ") + .append("ROWNUM as TMP_ROW_NUM"); + sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ").append(this.getFromClause()); SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)); sql.append(")) WHERE ").append(rowNumClause); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/PostgresPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/PostgresPagingQueryProvider.java index 83d3edc8..dea8e9a2 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/PostgresPagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/PostgresPagingQueryProvider.java @@ -29,8 +29,7 @@ public class PostgresPagingQueryProvider extends AbstractSqlPagingQueryProvider @Override public String getPageQuery(Pageable pageable) { - String limitClause = new StringBuilder().append("LIMIT ") - .append(pageable.getPageSize()).append(" OFFSET ") + String limitClause = new StringBuilder().append("LIMIT ").append(pageable.getPageSize()).append(" OFFSET ") .append(pageable.getOffset()).toString(); return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBean.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBean.java index c5369ec8..cc407d88 100755 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBean.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBean.java @@ -47,8 +47,7 @@ import static org.springframework.cloud.task.repository.support.DatabaseType.SQL * * @author Glenn Renfro */ -public class SqlPagingQueryProviderFactoryBean - implements FactoryBean { +public class SqlPagingQueryProviderFactoryBean implements FactoryBean { private DataSource dataSource; @@ -134,20 +133,16 @@ public class SqlPagingQueryProviderFactoryBean DatabaseType type; try { - type = this.databaseType != null - ? DatabaseType.valueOf(this.databaseType.toUpperCase()) + type = this.databaseType != null ? DatabaseType.valueOf(this.databaseType.toUpperCase()) : DatabaseType.fromMetaData(this.dataSource); } catch (MetaDataAccessException e) { throw new IllegalArgumentException( - "Could not inspect meta data for database type. You have to supply it explicitly.", - e); + "Could not inspect meta data for database type. You have to supply it explicitly.", e); } AbstractSqlPagingQueryProvider provider = this.providers.get(type); - Assert.state(provider != null, - "Should not happen: missing PagingQueryProvider for DatabaseType=" - + type); + Assert.state(provider != null, "Should not happen: missing PagingQueryProvider for DatabaseType=" + type); provider.setFromClause(this.fromClause); provider.setWhereClause(this.whereClause); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryUtils.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryUtils.java index 1c08ebf4..78173a1b 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryUtils.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryUtils.java @@ -37,13 +37,11 @@ public final class SqlPagingQueryUtils { * @param limitClause the implementation specific top clause to be used * @return the generated query */ - public static String generateLimitJumpToQuery(AbstractSqlPagingQueryProvider provider, - String limitClause) { + public static String generateLimitJumpToQuery(AbstractSqlPagingQueryProvider provider, String limitClause) { StringBuilder sql = new StringBuilder(); sql.append("SELECT ").append(provider.getSelectClause()); sql.append(" FROM ").append(provider.getFromClause()); - sql.append(provider.getWhereClause() == null ? "" - : " WHERE " + provider.getWhereClause()); + sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause()); sql.append(" ORDER BY ").append(buildSortClause(provider)); sql.append(" ").append(limitClause); @@ -57,14 +55,11 @@ public final class SqlPagingQueryUtils { * @param topClause the implementation specific top clause to be used * @return the generated query */ - public static String generateTopJumpToQuery(AbstractSqlPagingQueryProvider provider, - String topClause) { + public static String generateTopJumpToQuery(AbstractSqlPagingQueryProvider provider, String topClause) { StringBuilder sql = new StringBuilder(); - sql.append("SELECT ").append(topClause).append(" ") - .append(provider.getSelectClause()); + sql.append("SELECT ").append(topClause).append(" ").append(provider.getSelectClause()); sql.append(" FROM ").append(provider.getFromClause()); - sql.append(provider.getWhereClause() == null ? "" - : " WHERE " + provider.getWhereClause()); + sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause()); sql.append(" ORDER BY ").append(buildSortClause(provider)); return sql.toString(); @@ -76,8 +71,8 @@ public final class SqlPagingQueryUtils { * @param remainingPageQuery if true assumes more will be appended to where clause * @param sql the sql statement to be appended. */ - public static void buildWhereClause(AbstractSqlPagingQueryProvider provider, - boolean remainingPageQuery, StringBuilder sql) { + public static void buildWhereClause(AbstractSqlPagingQueryProvider provider, boolean remainingPageQuery, + StringBuilder sql) { if (remainingPageQuery) { sql.append(" WHERE "); if (provider.getWhereClause() != null) { @@ -87,8 +82,7 @@ public final class SqlPagingQueryUtils { } } else { - sql.append(provider.getWhereClause() == null ? "" - : " WHERE " + provider.getWhereClause()); + sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause()); } } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlServerPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlServerPagingQueryProvider.java index a7d01e66..21a95415 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlServerPagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/SqlServerPagingQueryProvider.java @@ -31,16 +31,14 @@ public class SqlServerPagingQueryProvider extends AbstractSqlPagingQueryProvider public String getPageQuery(Pageable pageable) { long offset = pageable.getOffset() + 1; return generateRowNumSqlQueryWithNesting(getSelectClause(), false, - "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " - + (offset + pageable.getPageSize())); + "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize())); } - private String generateRowNumSqlQueryWithNesting(String selectClause, - boolean remainingPageQuery, String rowNumClause) { + private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery, + String rowNumClause) { StringBuilder sql = new StringBuilder(); - sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ") - .append(selectClause).append(", ").append("ROW_NUMBER() OVER (ORDER BY ") - .append(SqlPagingQueryUtils.buildSortClause(this)) + sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ") + .append("ROW_NUMBER() OVER (ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)) .append(") AS TMP_ROW_NUM ").append(" FROM ").append(getFromClause()); SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql); sql.append(") TASK_EXECUTION_PAGE "); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/DatabaseType.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/DatabaseType.java index d26da06e..7a27fb48 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/DatabaseType.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/DatabaseType.java @@ -109,24 +109,22 @@ public enum DatabaseType { * @return DatabaseType The database type associated with the datasource. * @throws MetaDataAccessException thrown if failure occurs on metadata lookup. */ - public static DatabaseType fromMetaData(DataSource dataSource) - throws SQLException, MetaDataAccessException { - String databaseProductName = JdbcUtils - .extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() { + public static DatabaseType fromMetaData(DataSource dataSource) throws SQLException, MetaDataAccessException { + String databaseProductName = JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() { - @Override - public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException { - return dbmd.getDatabaseProductName(); - } - }).toString(); - if (StringUtils.hasText(databaseProductName) - && !databaseProductName.equals("DB2/Linux") + @Override + public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException { + return dbmd.getDatabaseProductName(); + } + }).toString(); + if (StringUtils.hasText(databaseProductName) && !databaseProductName.equals("DB2/Linux") && databaseProductName.startsWith("DB2")) { String databaseProductVersion = JdbcUtils .extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() { @Override - public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException { + public Object processMetaData(DatabaseMetaData dbmd) + throws SQLException, MetaDataAccessException { return dbmd.getDatabaseProductVersion(); } }).toString(); @@ -139,8 +137,7 @@ public enum DatabaseType { } else if (databaseProductName.indexOf("AS") != -1 && (databaseProductVersion.startsWith("QSQ") || databaseProductVersion - .substring(databaseProductVersion.indexOf('V')) - .matches("V\\dR\\d[mM]\\d"))) { + .substring(databaseProductVersion.indexOf('V')).matches("V\\dR\\d[mM]\\d"))) { databaseProductName = "DB2AS400"; } else { @@ -164,8 +161,7 @@ public enum DatabaseType { productName = "MySQL"; } if (!dbNameMap.containsKey(productName)) { - throw new IllegalArgumentException( - "DatabaseType not found for product name: [" + productName + "]"); + throw new IllegalArgumentException("DatabaseType not found for product name: [" + productName + "]"); } else { return dbNameMap.get(productName); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorer.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorer.java index 4d571896..1db34860 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorer.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorer.java @@ -39,8 +39,7 @@ public class SimpleTaskExplorer implements TaskExplorer { private TaskExecutionDao taskExecutionDao; public SimpleTaskExplorer(TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean) { - Assert.notNull(taskExecutionDaoFactoryBean, - "taskExecutionDaoFactoryBean must not be null"); + Assert.notNull(taskExecutionDaoFactoryBean, "taskExecutionDaoFactoryBean must not be null"); try { this.taskExecutionDao = taskExecutionDaoFactoryBean.getObject(); @@ -56,8 +55,7 @@ public class SimpleTaskExplorer implements TaskExplorer { } @Override - public Page findRunningTaskExecutions(String taskName, - Pageable pageable) { + public Page findRunningTaskExecutions(String taskName, Pageable pageable) { return this.taskExecutionDao.findRunningTaskExecutions(taskName, pageable); } @@ -82,8 +80,7 @@ public class SimpleTaskExplorer implements TaskExplorer { } @Override - public Page findTaskExecutionsByName(String taskName, - Pageable pageable) { + public Page findTaskExecutionsByName(String taskName, Pageable pageable) { return this.taskExecutionDao.findTaskExecutionsByName(taskName, pageable); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolver.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolver.java index 8371ea63..40d54955 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolver.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolver.java @@ -46,8 +46,7 @@ public class SimpleTaskNameResolver implements TaskNameResolver, ApplicationCont } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskRepository.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskRepository.java index 96b4e101..d5b0fdd0 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskRepository.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SimpleTaskRepository.java @@ -65,19 +65,15 @@ public class SimpleTaskRepository implements TaskRepository { private int maxErrorMessageSize = MAX_ERROR_MESSAGE_SIZE; - public SimpleTaskRepository( - FactoryBean taskExecutionDaoFactoryBean) { - Assert.notNull(taskExecutionDaoFactoryBean, - "A FactoryBean that provides a TaskExecutionDao is required"); + public SimpleTaskRepository(FactoryBean taskExecutionDaoFactoryBean) { + Assert.notNull(taskExecutionDaoFactoryBean, "A FactoryBean that provides a TaskExecutionDao is required"); this.taskExecutionDaoFactoryBean = taskExecutionDaoFactoryBean; } - public SimpleTaskRepository(FactoryBean taskExecutionDaoFactoryBean, - Integer maxExitMessageSize, Integer maxTaskNameSize, - Integer maxErrorMessageSize) { - Assert.notNull(taskExecutionDaoFactoryBean, - "A FactoryBean that provides a TaskExecutionDao is required"); + public SimpleTaskRepository(FactoryBean taskExecutionDaoFactoryBean, Integer maxExitMessageSize, + Integer maxTaskNameSize, Integer maxErrorMessageSize) { + Assert.notNull(taskExecutionDaoFactoryBean, "A FactoryBean that provides a TaskExecutionDao is required"); if (maxTaskNameSize != null) { this.maxTaskNameSize = maxTaskNameSize; } @@ -91,24 +87,21 @@ public class SimpleTaskRepository implements TaskRepository { } @Override - public TaskExecution completeTaskExecution(long executionId, Integer exitCode, - Date endTime, String exitMessage) { + public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) { return completeTaskExecution(executionId, exitCode, endTime, exitMessage, null); } @Override - public TaskExecution completeTaskExecution(long executionId, Integer exitCode, - Date endTime, String exitMessage, String errorMessage) { + public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage, + String errorMessage) { initialize(); validateCompletedTaskExitInformation(executionId, exitCode, endTime); exitMessage = trimMessage(exitMessage, this.maxExitMessageSize); errorMessage = trimMessage(errorMessage, this.maxErrorMessageSize); - this.taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime, - exitMessage, errorMessage); - logger.debug("Updating: TaskExecution with executionId=" + executionId - + " with the following {" + "exitCode=" + exitCode + ", endTime=" - + endTime + ", exitMessage='" + exitMessage + '\'' + ", errorMessage='" + this.taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime, exitMessage, errorMessage); + logger.debug("Updating: TaskExecution with executionId=" + executionId + " with the following {" + "exitCode=" + + exitCode + ", endTime=" + endTime + ", exitMessage='" + exitMessage + '\'' + ", errorMessage='" + errorMessage + '\'' + '}'); return this.taskExecutionDao.getTaskExecution(executionId); @@ -118,9 +111,8 @@ public class SimpleTaskRepository implements TaskRepository { public TaskExecution createTaskExecution(TaskExecution taskExecution) { initialize(); validateCreateInformation(taskExecution); - TaskExecution daoTaskExecution = this.taskExecutionDao.createTaskExecution( - taskExecution.getTaskName(), taskExecution.getStartTime(), - taskExecution.getArguments(), taskExecution.getExternalExecutionId(), + TaskExecution daoTaskExecution = this.taskExecutionDao.createTaskExecution(taskExecution.getTaskName(), + taskExecution.getStartTime(), taskExecution.getArguments(), taskExecution.getExternalExecutionId(), taskExecution.getParentExecutionId()); logger.debug("Creating: " + taskExecution.toString()); return daoTaskExecution; @@ -129,8 +121,8 @@ public class SimpleTaskRepository implements TaskRepository { @Override public TaskExecution createTaskExecution(String name) { initialize(); - TaskExecution taskExecution = this.taskExecutionDao.createTaskExecution(name, - null, Collections.emptyList(), null); + TaskExecution taskExecution = this.taskExecutionDao.createTaskExecution(name, null, + Collections.emptyList(), null); logger.debug("Creating: " + taskExecution.toString()); return taskExecution; } @@ -141,10 +133,9 @@ public class SimpleTaskRepository implements TaskRepository { } @Override - public TaskExecution startTaskExecution(long executionid, String taskName, - Date startTime, List arguments, String externalExecutionId) { - return startTaskExecution(executionid, taskName, startTime, arguments, - externalExecutionId, null); + public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List arguments, + String externalExecutionId) { + return startTaskExecution(executionid, taskName, startTime, arguments, externalExecutionId, null); } @Override @@ -154,13 +145,11 @@ public class SimpleTaskRepository implements TaskRepository { } @Override - public TaskExecution startTaskExecution(long executionid, String taskName, - Date startTime, List arguments, String externalExecutionId, - Long parentExecutionId) { + public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List arguments, + String externalExecutionId, Long parentExecutionId) { initialize(); - TaskExecution taskExecution = this.taskExecutionDao.startTaskExecution( - executionid, taskName, startTime, arguments, externalExecutionId, - parentExecutionId); + TaskExecution taskExecution = this.taskExecutionDao.startTaskExecution(executionid, taskName, startTime, + arguments, externalExecutionId, parentExecutionId); logger.debug("Starting: " + taskExecution.toString()); return taskExecution; } @@ -181,8 +170,7 @@ public class SimpleTaskRepository implements TaskRepository { this.initialized = true; } catch (Exception e) { - throw new IllegalStateException("Unable to create the TaskExecutionDao", - e); + throw new IllegalStateException("Unable to create the TaskExecutionDao", e); } } } @@ -192,18 +180,14 @@ public class SimpleTaskRepository implements TaskRepository { * @param taskExecution task execution to validate */ private void validateCreateInformation(TaskExecution taskExecution) { - Assert.notNull(taskExecution.getStartTime(), - "TaskExecution start time cannot be null."); + Assert.notNull(taskExecution.getStartTime(), "TaskExecution start time cannot be null."); - if (taskExecution.getTaskName() != null - && taskExecution.getTaskName().length() > this.maxTaskNameSize) { - throw new IllegalArgumentException( - "TaskName length exceeds " + this.maxTaskNameSize + " characters"); + if (taskExecution.getTaskName() != null && taskExecution.getTaskName().length() > this.maxTaskNameSize) { + throw new IllegalArgumentException("TaskName length exceeds " + this.maxTaskNameSize + " characters"); } } - private void validateCompletedTaskExitInformation(long executionId, Integer exitCode, - Date endTime) { + private void validateCompletedTaskExitInformation(long executionId, Integer exitCode, Date endTime) { Assert.notNull(exitCode, "exitCode should not be null"); Assert.isTrue(exitCode >= 0, "exit code must be greater than or equal to zero"); Assert.notNull(endTime, "TaskExecution endTime cannot be null."); diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementer.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementer.java index e876d1c1..d8bc186d 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementer.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementer.java @@ -22,6 +22,7 @@ import org.springframework.jdbc.support.incrementer.AbstractSequenceMaxValueIncr /** * Incrementer using SQL Server's sequence. + * * @author Glenn Renfro * @since 2.3.2 */ @@ -30,8 +31,10 @@ public class SqlServerSequenceMaxValueIncrementer extends AbstractSequenceMaxVal SqlServerSequenceMaxValueIncrementer(DataSource dataSource, String incrementerName) { super(dataSource, incrementerName); } + @Override protected String getSequenceQuery() { return "select next value for " + getIncrementerName(); } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBean.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBean.java index 409cab1c..e05fbfce 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBean.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBean.java @@ -100,8 +100,8 @@ public class TaskExecutionDaoFactoryBean implements FactoryBean { - SingleInstanceTaskListener singleInstanceTaskListener = context - .getBean(SingleInstanceTaskListener.class); + SingleInstanceTaskListener singleInstanceTaskListener = context.getBean(SingleInstanceTaskListener.class); - assertThat(singleInstanceTaskListener) - .as("singleInstanceTaskListener should not be null").isNotNull(); + assertThat(singleInstanceTaskListener).as("singleInstanceTaskListener should not be null").isNotNull(); - assertThat(SingleInstanceTaskListener.class) - .isEqualTo(singleInstanceTaskListener.getClass()); + assertThat(SingleInstanceTaskListener.class).isEqualTo(singleInstanceTaskListener.getClass()); }); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationWithDataSourceTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationWithDataSourceTests.java index d2b79b35..1aa81fea 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationWithDataSourceTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationWithDataSourceTests.java @@ -41,20 +41,16 @@ public class SimpleSingleTaskAutoConfigurationWithDataSourceTests { public void testConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class, EmbeddedDataSourceConfiguration.class)) .withPropertyValues("spring.cloud.task.singleInstanceEnabled=true"); applicationContextRunner.run((context) -> { - SingleInstanceTaskListener singleInstanceTaskListener = context - .getBean(SingleInstanceTaskListener.class); + SingleInstanceTaskListener singleInstanceTaskListener = context.getBean(SingleInstanceTaskListener.class); - assertThat(singleInstanceTaskListener) - .as("singleInstanceTaskListener should not be null").isNotNull(); + assertThat(singleInstanceTaskListener).as("singleInstanceTaskListener should not be null").isNotNull(); - assertThat(SingleInstanceTaskListener.class) - .isEqualTo(singleInstanceTaskListener.getClass()); + assertThat(SingleInstanceTaskListener.class).isEqualTo(singleInstanceTaskListener.getClass()); }); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleTaskAutoConfigurationTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleTaskAutoConfigurationTests.java index 494b6200..6a7d2341 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleTaskAutoConfigurationTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleTaskAutoConfigurationTests.java @@ -62,10 +62,8 @@ public class SimpleTaskAutoConfigurationTests { @Test public void testRepository() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)); applicationContextRunner.run((context) -> { TaskRepository taskRepository = context.getBean(TaskRepository.class); @@ -78,8 +76,7 @@ public class SimpleTaskAutoConfigurationTests { @Test public void testAutoConfigurationDisabled() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withPropertyValues("spring.cloud.task.autoconfiguration.enabled=false"); Executable executable = () -> { @@ -87,17 +84,16 @@ public class SimpleTaskAutoConfigurationTests { context.getBean(TaskRepository.class); }); }; - verifyExceptionThrown(NoSuchBeanDefinitionException.class, "No qualifying " - + "bean of type 'org.springframework.cloud.task.repository.TaskRepository' " - + "available", executable); + verifyExceptionThrown( + NoSuchBeanDefinitionException.class, "No qualifying " + + "bean of type 'org.springframework.cloud.task.repository.TaskRepository' " + "available", + executable); } @Test public void testRepositoryInitialized() { - ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(TaskLifecycleListenerConfiguration.class); applicationContextRunner.run((context) -> { @@ -108,14 +104,12 @@ public class SimpleTaskAutoConfigurationTests { @Test public void testRepositoryInitializedWithLazyInitialization() { - ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withInitializer((context) -> context - .addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .withConfiguration(AutoConfigurations.of( - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) - .withUserConfiguration(TaskLifecycleListenerConfiguration.class); + ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, + SingleTaskConfiguration.class)) + .withUserConfiguration(TaskLifecycleListenerConfiguration.class); applicationContextRunner.run((context) -> { TaskExplorer taskExplorer = context.getBean(TaskExplorer.class); assertThat(taskExplorer.getTaskExecutionCount()).isEqualTo(1L); @@ -125,47 +119,42 @@ public class SimpleTaskAutoConfigurationTests { @Test public void testRepositoryNotInitialized() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) + .withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, + SingleTaskConfiguration.class)) .withUserConfiguration(TaskLifecycleListenerConfiguration.class) .withPropertyValues("spring.cloud.task.tablePrefix=foobarless"); - verifyExceptionThrownDefaultExecutable(ApplicationContextException.class, - applicationContextRunner); + verifyExceptionThrownDefaultExecutable(ApplicationContextException.class, applicationContextRunner); } @Test public void testMultipleConfigurers() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(MultipleConfigurers.class); verifyExceptionThrownDefaultExecutable(BeanCreationException.class, - "Error creating bean " - + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed", + "Error creating bean " + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed", applicationContextRunner); } @Test public void testMultipleDataSources() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(MultipleDataSources.class); verifyExceptionThrownDefaultExecutable(BeanCreationException.class, - "Error creating bean " - + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed", + "Error creating bean " + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed", applicationContextRunner); } - public void verifyExceptionThrownDefaultExecutable(Class classToCheck, ApplicationContextRunner applicationContextRunner) { + public void verifyExceptionThrownDefaultExecutable(Class classToCheck, + ApplicationContextRunner applicationContextRunner) { Executable executable = () -> { applicationContextRunner.run((context) -> { Throwable expectedException = context.getStartupFailure(); @@ -188,10 +177,8 @@ public class SimpleTaskAutoConfigurationTests { verifyExceptionThrown(classToCheck, message, executable); } - public void verifyExceptionThrown(Class classToCheck, String message, - Executable executable) { - assertThatExceptionOfType(classToCheck).isThrownBy(executable::execute) - .withMessage(message); + public void verifyExceptionThrown(Class classToCheck, String message, Executable executable) { + assertThatExceptionOfType(classToCheck).isThrownBy(executable::execute).withMessage(message); } /** @@ -200,16 +187,13 @@ public class SimpleTaskAutoConfigurationTests { */ @Test public void testWithDataSourceProxy() { - ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(DataSourceProxyConfiguration.class); applicationContextRunner.run((context) -> { assertThat(context.getBeanNamesForType(DataSource.class).length).isEqualTo(2); - SimpleTaskAutoConfiguration taskConfiguration = context - .getBean(SimpleTaskAutoConfiguration.class); + SimpleTaskAutoConfiguration taskConfiguration = context.getBean(SimpleTaskAutoConfiguration.class); assertThat(taskConfiguration).isNotNull(); assertThat(taskConfiguration.taskExplorer()).isNotNull(); }); @@ -255,10 +239,9 @@ public class SimpleTaskAutoConfigurationTests { public BeanDefinitionHolder proxyDataSource() { GenericBeanDefinition proxyBeanDefinition = new GenericBeanDefinition(); proxyBeanDefinition.setBeanClassName("javax.sql.DataSource"); - BeanDefinitionHolder myDataSource = new BeanDefinitionHolder( - proxyBeanDefinition, "dataSource2"); - ScopedProxyUtils.createScopedProxy(myDataSource, - (BeanDefinitionRegistry) this.context.getBeanFactory(), true); + BeanDefinitionHolder myDataSource = new BeanDefinitionHolder(proxyBeanDefinition, "dataSource2"); + ScopedProxyUtils.createScopedProxy(myDataSource, (BeanDefinitionRegistry) this.context.getBeanFactory(), + true); return myDataSource; } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskCoreTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskCoreTests.java index e52e24fe..95bdba91 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskCoreTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskCoreTests.java @@ -72,17 +72,16 @@ public class TaskCoreTests { @Test public void successfulTaskTest(CapturedOutput capturedOutput) { this.applicationContext = SpringApplication.run(TaskConfiguration.class, - "--spring.cloud.task.closecontext.enable=false", - "--spring.cloud.task.name=" + TASK_NAME, + "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false"); String output = capturedOutput.toString(); - assertThat(output.contains(CREATE_TASK_MESSAGE)) - .as("Test results do not show create task message: " + output).isTrue(); - assertThat(output.contains(UPDATE_TASK_MESSAGE)) - .as("Test results do not show success message: " + output).isTrue(); - assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)) - .as("Test results have incorrect exit code: " + output).isTrue(); + assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output) + .isTrue(); + assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output) + .isTrue(); + assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output) + .isTrue(); } /** @@ -90,76 +89,63 @@ public class TaskCoreTests { */ @Test public void successfulTaskTestWithAnnotation(CapturedOutput capturedOutput) { - this.applicationContext = SpringApplication.run( - TaskConfigurationWithAnotation.class, - "--spring.cloud.task.closecontext.enable=false", - "--spring.cloud.task.name=" + TASK_NAME, + this.applicationContext = SpringApplication.run(TaskConfigurationWithAnotation.class, + "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false"); String output = capturedOutput.toString(); - assertThat(output.contains(CREATE_TASK_MESSAGE)) - .as("Test results do not show create task message: " + output).isTrue(); - assertThat(output.contains(UPDATE_TASK_MESSAGE)) - .as("Test results do not show success message: " + output).isTrue(); - assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)) - .as("Test results have incorrect exit code: " + output).isTrue(); + assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output) + .isTrue(); + assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output) + .isTrue(); + assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output) + .isTrue(); } @Test public void exceptionTaskTest(CapturedOutput capturedOutput) { boolean exceptionFired = false; try { - this.applicationContext = SpringApplication.run( - TaskExceptionConfiguration.class, - "--spring.cloud.task.closecontext.enable=false", - "--spring.cloud.task.name=" + TASK_NAME, + this.applicationContext = SpringApplication.run(TaskExceptionConfiguration.class, + "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false"); } catch (IllegalStateException exception) { exceptionFired = true; } - assertThat(exceptionFired).as("An IllegalStateException should have been thrown") - .isTrue(); + assertThat(exceptionFired).as("An IllegalStateException should have been thrown").isTrue(); String output = capturedOutput.toString(); - assertThat(output.contains(CREATE_TASK_MESSAGE)) - .as("Test results do not show create task message: " + output).isTrue(); - assertThat(output.contains(UPDATE_TASK_MESSAGE)) - .as("Test results do not show success message: " + output).isTrue(); - assertThat(output.contains(EXCEPTION_EXIT_CODE_MESSAGE)) - .as("Test results have incorrect exit code: " + output).isTrue(); - assertThat(output.contains(ERROR_MESSAGE)) - .as("Test results have incorrect exit message: " + output).isTrue(); - assertThat(output.contains(EXCEPTION_MESSAGE)) - .as("Test results have exception message: " + output).isTrue(); + assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output) + .isTrue(); + assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output) + .isTrue(); + assertThat(output.contains(EXCEPTION_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output) + .isTrue(); + assertThat(output.contains(ERROR_MESSAGE)).as("Test results have incorrect exit message: " + output).isTrue(); + assertThat(output.contains(EXCEPTION_MESSAGE)).as("Test results have exception message: " + output).isTrue(); } @Test public void invalidExecutionId(CapturedOutput capturedOutput) { boolean exceptionFired = false; try { - this.applicationContext = SpringApplication.run( - TaskExceptionConfiguration.class, - "--spring.cloud.task.closecontext.enable=false", - "--spring.cloud.task.name=" + TASK_NAME, - "--spring.main.web-environment=false", - "--spring.cloud.task.executionid=55"); + this.applicationContext = SpringApplication.run(TaskExceptionConfiguration.class, + "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, + "--spring.main.web-environment=false", "--spring.cloud.task.executionid=55"); } catch (ApplicationContextException exception) { exceptionFired = true; } - assertThat(exceptionFired) - .as("An ApplicationContextException should have been thrown").isTrue(); + assertThat(exceptionFired).as("An ApplicationContextException should have been thrown").isTrue(); String output = capturedOutput.toString(); assertThat(output.contains(EXCEPTION_INVALID_TASK_EXECUTION_ID)) - .as("Test results do not show the correct exception message: " + output) - .isTrue(); + .as("Test results do not show the correct exception message: " + output).isTrue(); } @EnableTask - @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) public static class TaskConfiguration { @Bean @@ -174,8 +160,7 @@ public class TaskCoreTests { } @EnableTask - @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) public static class TaskConfigurationWithAnotation { @Bean @@ -190,8 +175,7 @@ public class TaskCoreTests { } @EnableTask - @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) public static class TaskExceptionConfiguration { @Bean diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerDefaultTaskConfigurerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerDefaultTaskConfigurerTests.java index 6d010e1c..8c2d0c3d 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerDefaultTaskConfigurerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerDefaultTaskConfigurerTests.java @@ -43,8 +43,7 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; * @since 2.0.0 */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class }) +@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, EmbeddedDataSourceConfiguration.class }) @DirtiesContext public class TaskRepositoryInitializerDefaultTaskConfigurerTests { diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerNoDataSourceTaskConfigurerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerNoDataSourceTaskConfigurerTests.java index c2877001..d24ee61a 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerNoDataSourceTaskConfigurerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/TaskRepositoryInitializerNoDataSourceTaskConfigurerTests.java @@ -44,9 +44,8 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; * @since 2.0.0 */ @ExtendWith(SpringExtension.class) -@ContextConfiguration( - classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class, - EmbeddedDataSourceConfiguration.class, DefaultTaskConfigurer.class }) +@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class, + EmbeddedDataSourceConfiguration.class, DefaultTaskConfigurer.class }) public class TaskRepositoryInitializerNoDataSourceTaskConfigurerTests { @Autowired diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurerTests.java index ca219b7a..92ba2aee 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/DefaultTaskConfigurerTests.java @@ -51,48 +51,39 @@ public class DefaultTaskConfigurerTests { public void resourcelessTransactionManagerTest() { DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) - .isEqualTo( - "org.springframework.batch.support.transaction.ResourcelessTransactionManager"); + .isEqualTo("org.springframework.batch.support.transaction.ResourcelessTransactionManager"); defaultTaskConfigurer = new DefaultTaskConfigurer("foo"); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) - .isEqualTo( - "org.springframework.batch.support.transaction.ResourcelessTransactionManager"); + .isEqualTo("org.springframework.batch.support.transaction.ResourcelessTransactionManager"); } @Test public void testDefaultContext() throws Exception { AnnotationConfigApplicationContext localContext = new AnnotationConfigApplicationContext(); - localContext.register(EmbeddedDataSourceConfiguration.class, - EntityManagerConfiguration.class); + localContext.register(EmbeddedDataSourceConfiguration.class, EntityManagerConfiguration.class); localContext.refresh(); - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( - this.dataSource, TaskProperties.DEFAULT_TABLE_PREFIX, localContext); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, + TaskProperties.DEFAULT_TABLE_PREFIX, localContext); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) .isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager"); } @Test public void dataSourceTransactionManagerTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( - this.dataSource); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) - .isEqualTo( - "org.springframework.jdbc.datasource.DataSourceTransactionManager"); + .isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager"); defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO", null); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) - .isEqualTo( - "org.springframework.jdbc.datasource.DataSourceTransactionManager"); - defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO", - this.context); + .isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager"); + defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO", this.context); assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) - .isEqualTo( - "org.springframework.jdbc.datasource.DataSourceTransactionManager"); + .isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager"); } @Test public void taskExplorerTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( - this.dataSource); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource); assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull(); @@ -100,8 +91,7 @@ public class DefaultTaskConfigurerTests { @Test public void taskRepositoryTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( - this.dataSource); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource); assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull(); @@ -109,8 +99,7 @@ public class DefaultTaskConfigurerTests { @Test public void taskDataSource() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( - this.dataSource); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource); assertThat(defaultTaskConfigurer.getTaskDataSource()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); assertThat(defaultTaskConfigurer.getTaskDataSource()).isNull(); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/RepositoryTransactionManagerConfigurationTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/RepositoryTransactionManagerConfigurationTests.java index 9e9699bd..f782cf62 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/RepositoryTransactionManagerConfigurationTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/RepositoryTransactionManagerConfigurationTests.java @@ -50,17 +50,14 @@ public class RepositoryTransactionManagerConfigurationTests { @Test public void testZeroCustomTransactionManagerConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - ZeroTransactionManagerConfiguration.class)) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, ZeroTransactionManagerConfiguration.class)) .withPropertyValues("application.name=transactionManagerTask"); applicationContextRunner.run((context) -> { DataSource dataSource = context.getBean("dataSource", DataSource.class); - int taskExecutionCount = JdbcTestUtils - .countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION"); + int taskExecutionCount = JdbcTestUtils.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION"); assertThat(taskExecutionCount).isEqualTo(1); }); @@ -78,29 +75,24 @@ public class RepositoryTransactionManagerConfigurationTests { private void testConfiguration(Class configurationClass) { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, configurationClass)) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, configurationClass)) .withPropertyValues("application.name=transactionManagerTask"); applicationContextRunner.run((context) -> { DataSource dataSource = context.getBean("dataSource", DataSource.class); - int taskExecutionCount = JdbcTestUtils - .countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION"); + int taskExecutionCount = JdbcTestUtils.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION"); // Verify that the create call was rolled back assertThat(taskExecutionCount).isEqualTo(0); // Execute a new create call so that things close cleanly - TaskRepository taskRepository = context.getBean("taskRepository", - TaskRepository.class); + TaskRepository taskRepository = context.getBean("taskRepository", TaskRepository.class); - TaskExecution taskExecution = taskRepository - .createTaskExecution("transactionManagerTask"); - taskExecution = taskRepository.startTaskExecution( - taskExecution.getExecutionId(), taskExecution.getTaskName(), - new Date(), new ArrayList<>(0), null); + TaskExecution taskExecution = taskRepository.createTaskExecution("transactionManagerTask"); + taskExecution = taskRepository.startTaskExecution(taskExecution.getExecutionId(), + taskExecution.getTaskName(), new Date(), new ArrayList<>(0), null); TaskLifecycleListener listener = context.getBean(TaskLifecycleListener.class); @@ -129,8 +121,7 @@ public class RepositoryTransactionManagerConfigurationTests { public static class SingleTransactionManagerConfiguration { @Bean - public TaskConfigurer taskConfigurer(DataSource dataSource, - PlatformTransactionManager transactionManager) { + public TaskConfigurer taskConfigurer(DataSource dataSource, PlatformTransactionManager transactionManager) { return new DefaultTaskConfigurer(dataSource) { @Override public PlatformTransactionManager getTransactionManager() { @@ -156,8 +147,7 @@ public class RepositoryTransactionManagerConfigurationTests { public static class MultipleTransactionManagerConfiguration { @Bean - public TaskConfigurer taskConfigurer(DataSource dataSource, - PlatformTransactionManager transactionManager) { + public TaskConfigurer taskConfigurer(DataSource dataSource, PlatformTransactionManager transactionManager) { return new DefaultTaskConfigurer(dataSource) { @Override public PlatformTransactionManager getTransactionManager() { @@ -188,8 +178,7 @@ public class RepositoryTransactionManagerConfigurationTests { } - private static class TestDataSourceTransactionManager - extends DataSourceTransactionManager { + private static class TestDataSourceTransactionManager extends DataSourceTransactionManager { protected TestDataSourceTransactionManager(DataSource dataSource) { super(dataSource); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TaskPropertiesTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TaskPropertiesTests.java index 4dc66639..c07cf3ec 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TaskPropertiesTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TaskPropertiesTests.java @@ -28,10 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @ExtendWith(SpringExtension.class) -@SpringBootTest( - classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class }, - properties = { "spring.cloud.task.closecontextEnabled=false", - "spring.cloud.task.initialize-enabled=false" }) +@SpringBootTest(classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class }, + properties = { "spring.cloud.task.closecontextEnabled=false", "spring.cloud.task.initialize-enabled=false" }) public class TaskPropertiesTests { @Autowired diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TestConfiguration.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TestConfiguration.java index db4bbb02..b8833402 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TestConfiguration.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/TestConfiguration.java @@ -50,8 +50,7 @@ public class TestConfiguration implements InitializingBean { @Bean public TaskRepositoryInitializer taskRepositoryInitializer() throws Exception { - TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer( - new TaskProperties()); + TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(new TaskProperties()); taskRepositoryInitializer.setDataSource(this.dataSource); taskRepositoryInitializer.setResourceLoader(this.resourceLoader); taskRepositoryInitializer.afterPropertiesSet(); @@ -82,8 +81,7 @@ public class TestConfiguration implements InitializingBean { @Override public void afterPropertiesSet() { if (this.dataSource != null) { - this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean( - this.dataSource); + this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource); } else { this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/observation/ObservationIntegrationTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/observation/ObservationIntegrationTests.java index bd1a5abf..ebe2bcae 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/observation/ObservationIntegrationTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/configuration/observation/ObservationIntegrationTests.java @@ -63,15 +63,15 @@ class ObservationIntegrationTests { void testSuccessfulObservation() { List finishedSpans = finishedSpans(); - SpansAssert.then(finishedSpans) - .thenASpanWithNameEqualTo("my-command-line-runner") - .hasTag("spring.cloud.task.runner.bean-name", "myCommandLineRunner") - .backToSpans() - .thenASpanWithNameEqualTo("my-application-runner") - .hasTag("spring.cloud.task.runner.bean-name", "myApplicationRunner"); + SpansAssert.then(finishedSpans).thenASpanWithNameEqualTo("my-command-line-runner") + .hasTag("spring.cloud.task.runner.bean-name", "myCommandLineRunner").backToSpans() + .thenASpanWithNameEqualTo("my-application-runner") + .hasTag("spring.cloud.task.runner.bean-name", "myApplicationRunner"); MeterRegistryAssert.then(this.meterRegistry) - .hasTimerWithNameAndTags("spring.cloud.task.runner", KeyValues.of("spring.cloud.task.runner.bean-name", "myCommandLineRunner")) - .hasTimerWithNameAndTags("spring.cloud.task.runner", KeyValues.of("spring.cloud.task.runner.bean-name", "myApplicationRunner")); + .hasTimerWithNameAndTags("spring.cloud.task.runner", + KeyValues.of("spring.cloud.task.runner.bean-name", "myCommandLineRunner")) + .hasTimerWithNameAndTags("spring.cloud.task.runner", + KeyValues.of("spring.cloud.task.runner.bean-name", "myApplicationRunner")); } private List finishedSpans() { @@ -80,8 +80,12 @@ class ObservationIntegrationTests { @Configuration @EnableTask - @ImportAutoConfiguration({SimpleTaskAutoConfiguration.class, ObservationAutoConfiguration.class, ObservationTaskAutoConfiguration.class, BraveAutoConfiguration.class, MicrometerTracingAutoConfiguration.class, MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class, ZipkinAutoConfiguration.class}) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, ObservationAutoConfiguration.class, + ObservationTaskAutoConfiguration.class, BraveAutoConfiguration.class, + MicrometerTracingAutoConfiguration.class, MetricsAutoConfiguration.class, + CompositeMeterRegistryAutoConfiguration.class, ZipkinAutoConfiguration.class }) static class Config { + private static final Logger log = LoggerFactory.getLogger(Config.class); @Bean @@ -96,12 +100,16 @@ class ObservationIntegrationTests { @Bean CommandLineRunner myCommandLineRunner(Tracer tracer) { - return args -> log.info(" Hello from command line runner", tracer.currentSpan().context().traceId()); + return args -> log.info(" Hello from command line runner", + tracer.currentSpan().context().traceId()); } @Bean ApplicationRunner myApplicationRunner(Tracer tracer) { - return args -> log.info(" Hello from application runner", tracer.currentSpan().context().traceId()); + return args -> log.info(" Hello from application runner", + tracer.currentSpan().context().traceId()); } + } + } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExceptionTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExceptionTests.java index 271cb42c..5b49d073 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExceptionTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExceptionTests.java @@ -32,8 +32,7 @@ public class TaskExceptionTests { TaskException taskException = new TaskException(ERROR_MESSAGE); assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); - taskException = new TaskException(ERROR_MESSAGE, - new IllegalStateException(ERROR_MESSAGE)); + taskException = new TaskException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE)); assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); assertThat(taskException.getCause()).isNotNull(); assertThat(taskException.getCause().getMessage()).isEqualTo(ERROR_MESSAGE); @@ -44,8 +43,7 @@ public class TaskExceptionTests { TaskExecutionException taskException = new TaskExecutionException(ERROR_MESSAGE); assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); - taskException = new TaskExecutionException(ERROR_MESSAGE, - new IllegalStateException(ERROR_MESSAGE)); + taskException = new TaskExecutionException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE)); assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); assertThat(taskException.getCause()).isNotNull(); assertThat(taskException.getCause().getMessage()).isEqualTo(ERROR_MESSAGE); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExecutionListenerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExecutionListenerTests.java index d499fb34..a5456d20 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExecutionListenerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExecutionListenerTests.java @@ -80,10 +80,9 @@ public class TaskExecutionListenerTests { public void testTaskCreate() { setupContextForTaskExecutionListener(); DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context - .getBean( - DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); - TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + .getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); + TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), new Date(), null, + new ArrayList<>(), null, null); verifyListenerResults(false, false, taskExecution, taskExecutionListener); } @@ -101,12 +100,9 @@ public class TaskExecutionListenerTests { exceptionFired = true; } assertThat(exceptionFired).as("Exception should have fired").isTrue(); - assertThat(beforeTaskDidFireOnError) - .as("BeforeTask Listener should have executed").isTrue(); - assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed") - .isTrue(); - assertThat(failedTaskDidFireOnError) - .as("FailedTask Listener should have executed").isTrue(); + assertThat(beforeTaskDidFireOnError).as("BeforeTask Listener should have executed").isTrue(); + assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed").isTrue(); + assertThat(failedTaskDidFireOnError).as("FailedTask Listener should have executed").isTrue(); } /** @@ -123,10 +119,8 @@ public class TaskExecutionListenerTests { exceptionFired = true; } assertThat(exceptionFired).as("Exception should have fired").isTrue(); - assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed") - .isTrue(); - assertThat(failedTaskDidFireOnError) - .as("FailedTask Listener should not have executed").isTrue(); + assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed").isTrue(); + assertThat(failedTaskDidFireOnError).as("FailedTask Listener should not have executed").isTrue(); } /** @@ -137,18 +131,15 @@ public class TaskExecutionListenerTests { public void testAfterTaskErrorCreate() { setupContextForAfterTaskErrorAnnotatedListener(); AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener taskExecutionListener = this.context - .getBean( - AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class); - this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), - new String[0], this.context, Duration.ofSeconds(50))); + .getBean(AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context, + Duration.ofSeconds(50))); assertThat(taskExecutionListener.isTaskStartup()).isTrue(); assertThat(taskExecutionListener.isTaskEnd()).isTrue(); - assertThat(taskExecutionListener.getTaskExecution().getExitMessage()) - .isEqualTo(TestListener.END_MESSAGE); - assertThat(taskExecutionListener.getTaskExecution().getErrorMessage().contains( - "Failed to process @BeforeTask or @AfterTask annotation because: AfterTaskFailure")) - .isTrue(); + assertThat(taskExecutionListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE); + assertThat(taskExecutionListener.getTaskExecution().getErrorMessage() + .contains("Failed to process @BeforeTask or @AfterTask annotation because: AfterTaskFailure")).isTrue(); assertThat(taskExecutionListener.getThrowable()).isNull(); } @@ -160,13 +151,12 @@ public class TaskExecutionListenerTests { public void testTaskUpdate() { setupContextForTaskExecutionListener(); DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context - .getBean( - DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); - this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), - new String[0], this.context, Duration.ofSeconds(50))); + .getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context, + Duration.ofSeconds(50))); - TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), new Date(), null, new ArrayList<>(), + null, null); verifyListenerResults(true, false, taskExecution, taskExecutionListener); } @@ -180,15 +170,13 @@ public class TaskExecutionListenerTests { setupContextForTaskExecutionListener(); SpringApplication application = new SpringApplication(); DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context - .getBean( - DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); - this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], - this.context, exception)); + .getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); + this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception)); this.context.publishEvent( new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50))); - TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(), + null, null); verifyListenerResults(true, true, taskExecution, taskExecutionListener); } @@ -201,8 +189,8 @@ public class TaskExecutionListenerTests { setupContextForAnnotatedListener(); DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context .getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), new Date(), null, + new ArrayList<>(), null, null); verifyListenerResults(false, false, taskExecution, annotatedListener); } @@ -215,11 +203,11 @@ public class TaskExecutionListenerTests { setupContextForAnnotatedListener(); DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context .getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), - new String[0], this.context, Duration.ofSeconds(50))); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context, + Duration.ofSeconds(50))); - TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), new Date(), null, new ArrayList<>(), + null, null); verifyListenerResults(true, false, taskExecution, annotatedListener); } @@ -234,88 +222,71 @@ public class TaskExecutionListenerTests { SpringApplication application = new SpringApplication(); DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context .getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], - this.context, exception)); + this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception)); this.context.publishEvent( new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50))); - TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), - new Date(), null, new ArrayList<>(), null, null); + TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(), + null, null); verifyListenerResults(true, true, taskExecution, annotatedListener); } - private void verifyListenerResults(boolean isTaskEnd, boolean isTaskFailed, - TaskExecution taskExecution, TestListener actualListener) { + private void verifyListenerResults(boolean isTaskEnd, boolean isTaskFailed, TaskExecution taskExecution, + TestListener actualListener) { assertThat(actualListener.isTaskStartup()).isTrue(); assertThat(actualListener.isTaskEnd()).isEqualTo(isTaskEnd); assertThat(actualListener.isTaskFailed()).isEqualTo(isTaskFailed); if (isTaskFailed) { - assertThat(actualListener.getTaskExecution().getExitMessage()) - .isEqualTo(TestListener.END_MESSAGE); + assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE); assertThat(actualListener.getThrowable()).isNotNull(); - assertThat(actualListener.getThrowable() instanceof RuntimeException) - .isTrue(); + assertThat(actualListener.getThrowable() instanceof RuntimeException).isTrue(); assertThat(actualListener.getTaskExecution().getErrorMessage() - .startsWith("java.lang.RuntimeException: This was expected")) - .isTrue(); + .startsWith("java.lang.RuntimeException: This was expected")).isTrue(); } else if (isTaskEnd) { - assertThat(actualListener.getTaskExecution().getExitMessage()) - .isEqualTo(TestListener.END_MESSAGE); - assertThat(actualListener.getTaskExecution().getErrorMessage()) - .isEqualTo(taskExecution.getErrorMessage()); + assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE); + assertThat(actualListener.getTaskExecution().getErrorMessage()).isEqualTo(taskExecution.getErrorMessage()); assertThat(actualListener.getThrowable()).isNull(); } else { - assertThat(actualListener.getTaskExecution().getExitMessage()) - .isEqualTo(TestListener.START_MESSAGE); + assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.START_MESSAGE); assertThat(actualListener.getTaskExecution().getErrorMessage()).isNull(); assertThat(actualListener.getThrowable()).isNull(); } - assertThat(actualListener.getTaskExecution().getExecutionId()) - .isEqualTo(taskExecution.getExecutionId()); - assertThat(actualListener.getTaskExecution().getExitCode()) - .isEqualTo(taskExecution.getExitCode()); + assertThat(actualListener.getTaskExecution().getExecutionId()).isEqualTo(taskExecution.getExecutionId()); + assertThat(actualListener.getTaskExecution().getExitCode()).isEqualTo(taskExecution.getExitCode()); assertThat(actualListener.getTaskExecution().getExternalExecutionId()) .isEqualTo(taskExecution.getExternalExecutionId()); } private void setupContextForTaskExecutionListener() { - this.context = new AnnotationConfigApplicationContext( - DefaultTaskListenerConfiguration.class, TestDefaultConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(DefaultTaskListenerConfiguration.class, + TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.setId("testTask"); } private void setupContextForAnnotatedListener() { - this.context = new AnnotationConfigApplicationContext( - TestDefaultConfiguration.class, DefaultAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, + DefaultAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.setId("annotatedTask"); } private void setupContextForBeforeTaskErrorAnnotatedListener() { - this.context = new AnnotationConfigApplicationContext( - TestDefaultConfiguration.class, - BeforeTaskErrorAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, + BeforeTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.setId("beforeTaskAnnotatedTask"); } private void setupContextForFailedTaskErrorAnnotatedListener() { - this.context = new AnnotationConfigApplicationContext( - TestDefaultConfiguration.class, - FailedTaskErrorAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, + FailedTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.setId("failedTaskAnnotatedTask"); } private void setupContextForAfterTaskErrorAnnotatedListener() { - this.context = new AnnotationConfigApplicationContext( - TestDefaultConfiguration.class, - AfterTaskErrorAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, + AfterTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.setId("afterTaskAnnotatedTask"); } @@ -457,8 +428,7 @@ public class TaskExecutionListenerTests { return new TestTaskExecutionListener(); } - public static class TestTaskExecutionListener extends TestListener - implements TaskExecutionListener { + public static class TestTaskExecutionListener extends TestListener implements TaskExecutionListener { @Override public void onTaskStartup(TaskExecution taskExecution) { diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskLifecycleListenerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskLifecycleListenerTests.java index e24fa1d0..9921ddbe 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskLifecycleListenerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskLifecycleListenerTests.java @@ -74,8 +74,7 @@ public class TaskLifecycleListenerTests { public void setUp() { this.context = new AnnotationConfigApplicationContext(); this.context.setId("testTask"); - this.context.register(TestDefaultConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class); TestListener.getStartupOrderList().clear(); TestListener.getFailOrderList().clear(); TestListener.getEndOrderList().clear(); @@ -109,8 +108,8 @@ public class TaskLifecycleListenerTests { this.context.refresh(); this.taskExplorer = this.context.getBean(TaskExplorer.class); - this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), - new String[0], this.context, Duration.ofSeconds(50))); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context, + Duration.ofSeconds(50))); verifyTaskExecution(0, true, 0); } @@ -121,8 +120,7 @@ public class TaskLifecycleListenerTests { RuntimeException exception = new RuntimeException("This was expected"); SpringApplication application = new SpringApplication(); this.taskExplorer = this.context.getBean(TaskExplorer.class); - this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], - this.context, exception)); + this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception)); this.context.publishEvent( new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50))); @@ -140,17 +138,14 @@ public class TaskLifecycleListenerTests { SpringApplication application = new SpringApplication(); this.taskExplorer = this.context.getBean(TaskExplorer.class); this.context.publishEvent(new ExitCodeEvent(this.context, exitCode)); - this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], - this.context, exception)); + this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception)); this.context.publishEvent( new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50))); verifyTaskExecution(0, true, exitCode, exception, null); assertThat(TestListener.getStartupOrderList().size()).isEqualTo(2); - assertThat(TestListener.getStartupOrderList().get(0)) - .isEqualTo(Integer.valueOf(2)); - assertThat(TestListener.getStartupOrderList().get(1)) - .isEqualTo(Integer.valueOf(1)); + assertThat(TestListener.getStartupOrderList().get(0)).isEqualTo(Integer.valueOf(2)); + assertThat(TestListener.getStartupOrderList().get(1)).isEqualTo(Integer.valueOf(1)); assertThat(TestListener.getEndOrderList().size()).isEqualTo(2); assertThat(TestListener.getEndOrderList().get(0)).isEqualTo(Integer.valueOf(1)); @@ -166,8 +161,7 @@ public class TaskLifecycleListenerTests { public void testNoClosingOfContext() { try (ConfigurableApplicationContext applicationContext = SpringApplication.run( - new Class[] { TestDefaultConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }, + new Class[] { TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class }, new String[] { "--spring.cloud.task.closecontext_enabled=false" })) { assertThat(applicationContext.isActive()).isTrue(); } @@ -180,8 +174,7 @@ public class TaskLifecycleListenerTests { MutablePropertySources propertySources = environment.getPropertySources(); Map myMap = new HashMap<>(); myMap.put("spring.cloud.task.executionid", "55"); - propertySources - .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); this.context.setEnvironment(environment); this.context.refresh(); }); @@ -190,8 +183,7 @@ public class TaskLifecycleListenerTests { @Test public void testRestartExistingTask(CapturedOutput capturedOutput) { this.context.refresh(); - TaskLifecycleListener taskLifecycleListener = this.context - .getBean(TaskLifecycleListener.class); + TaskLifecycleListener taskLifecycleListener = this.context.getBean(TaskLifecycleListener.class); taskLifecycleListener.start(); String output = capturedOutput.toString(); assertThat(output.contains("Multiple start events have been received")) @@ -204,8 +196,7 @@ public class TaskLifecycleListenerTests { MutablePropertySources propertySources = environment.getPropertySources(); Map myMap = new HashMap<>(); myMap.put("spring.cloud.task.external-execution-id", "myid"); - propertySources - .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); this.context.setEnvironment(environment); this.context.refresh(); this.taskExplorer = this.context.getBean(TaskExplorer.class); @@ -219,8 +210,7 @@ public class TaskLifecycleListenerTests { MutablePropertySources propertySources = environment.getPropertySources(); Map myMap = new HashMap<>(); myMap.put("spring.cloud.task.parentExecutionId", 789); - propertySources - .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); this.context.setEnvironment(environment); this.context.refresh(); this.taskExplorer = this.context.getBean(TaskExplorer.class); @@ -228,8 +218,7 @@ public class TaskLifecycleListenerTests { verifyTaskExecution(0, false, null, null, null, 789L); } - private void verifyTaskExecution(int numberOfParams, boolean update, - Integer exitCode) { + private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode) { verifyTaskExecution(numberOfParams, update, exitCode, null, null); } @@ -237,21 +226,19 @@ public class TaskLifecycleListenerTests { verifyTaskExecution(numberOfParams, update, null, null, null); } - private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, - Throwable exception, String externalExecutionId) { - verifyTaskExecution(numberOfParams, update, exitCode, exception, - externalExecutionId, null); + private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, Throwable exception, + String externalExecutionId) { + verifyTaskExecution(numberOfParams, update, exitCode, exception, externalExecutionId, null); } - private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, - Throwable exception, String externalExecutionId, Long parentExecutionId) { + private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, Throwable exception, + String externalExecutionId, Long parentExecutionId) { Sort sort = Sort.by("id"); PageRequest request = PageRequest.of(0, Integer.MAX_VALUE, sort); - Page taskExecutionsByName = this.taskExplorer - .findTaskExecutionsByName("testTask", request); + Page taskExecutionsByName = this.taskExplorer.findTaskExecutionsByName("testTask", request); assertThat(taskExecutionsByName.iterator().hasNext()).isTrue(); TaskExecution taskExecution = taskExecutionsByName.iterator().next(); @@ -261,16 +248,14 @@ public class TaskLifecycleListenerTests { assertThat(taskExecution.getParentExecutionId()).isEqualTo(parentExecutionId); if (exception != null) { - assertThat(taskExecution.getErrorMessage() - .length() > exception.getStackTrace().length).isTrue(); + assertThat(taskExecution.getErrorMessage().length() > exception.getStackTrace().length).isTrue(); } else { assertThat(taskExecution.getExitMessage()).isNull(); } if (update) { - assertThat(taskExecution.getEndTime().getTime() >= taskExecution - .getStartTime().getTime()).isTrue(); + assertThat(taskExecution.getEndTime().getTime() >= taskExecution.getStartTime().getTime()).isTrue(); assertThat(taskExecution.getExitCode()).isNotNull(); } else { @@ -310,8 +295,7 @@ public class TaskLifecycleListenerTests { int i = 0; for (Map.Entry stringStringEntry : this.args.entrySet()) { - sourceArgs[i] = "--" + stringStringEntry.getKey() + "=" - + stringStringEntry.getValue(); + sourceArgs[i] = "--" + stringStringEntry.getKey() + "=" + stringStringEntry.getValue(); i++; } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskListenerExecutorObjectFactoryTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskListenerExecutorObjectFactoryTests.java index 347bc2dd..4e4b739e 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskListenerExecutorObjectFactoryTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskListenerExecutorObjectFactoryTests.java @@ -46,8 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @since 2.1.0 */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { - TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class }) +@ContextConfiguration(classes = { TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class }) @DirtiesContext public class TaskListenerExecutorObjectFactoryTests { @@ -77,8 +76,7 @@ public class TaskListenerExecutorObjectFactoryTests { public void setup(ConfigurableApplicationContext context) { taskExecutionListenerResults.clear(); - this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory( - context); + this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory(context); this.taskListenerExecutor = this.taskListenerExecutorObjectFactory.getObject(); } @@ -90,8 +88,7 @@ public class TaskListenerExecutorObjectFactoryTests { applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); validateSingleEntry(BEFORE_LISTENER); }); } @@ -104,8 +101,7 @@ public class TaskListenerExecutorObjectFactoryTests { applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor.onTaskFailed( - createSampleTaskExecution(FAIL_LISTENER), + this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER), new IllegalStateException("oops")); validateSingleEntry(FAIL_LISTENER); }); @@ -119,8 +115,7 @@ public class TaskListenerExecutorObjectFactoryTests { applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); + this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); validateSingleEntry(AFTER_LISTENER); }); } @@ -133,34 +128,26 @@ public class TaskListenerExecutorObjectFactoryTests { applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); - this.taskListenerExecutor.onTaskFailed( - createSampleTaskExecution(FAIL_LISTENER), + this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER), new IllegalStateException("oops")); - this.taskListenerExecutor - .onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); + this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); assertThat(taskExecutionListenerResults.size()).isEqualTo(3); - assertThat(taskExecutionListenerResults.get(0).getTaskName()) - .isEqualTo(BEFORE_LISTENER); - assertThat(taskExecutionListenerResults.get(1).getTaskName()) - .isEqualTo(FAIL_LISTENER); - assertThat(taskExecutionListenerResults.get(2).getTaskName()) - .isEqualTo(AFTER_LISTENER); + assertThat(taskExecutionListenerResults.get(0).getTaskName()).isEqualTo(BEFORE_LISTENER); + assertThat(taskExecutionListenerResults.get(1).getTaskName()).isEqualTo(FAIL_LISTENER); + assertThat(taskExecutionListenerResults.get(2).getTaskName()).isEqualTo(AFTER_LISTENER); }); } @Test public void verifyTaskStartupListenerWithMultipleInstances() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskExecutionListenerMultipleInstanceConfiguration.class); + .withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class); applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); validateSingleEventWithMultipleInstances(BEFORE_LISTENER); }); } @@ -168,14 +155,12 @@ public class TaskListenerExecutorObjectFactoryTests { @Test public void verifyTaskFailedListenerWithMultipleInstances() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskExecutionListenerMultipleInstanceConfiguration.class); + .withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class); applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor.onTaskFailed( - createSampleTaskExecution(FAIL_LISTENER), + this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER), new IllegalStateException("oops")); validateSingleEventWithMultipleInstances(FAIL_LISTENER); }); @@ -184,14 +169,12 @@ public class TaskListenerExecutorObjectFactoryTests { @Test public void verifyTaskEndListenerWithMultipleInstances() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskExecutionListenerMultipleInstanceConfiguration.class); + .withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class); applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); + this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); validateSingleEventWithMultipleInstances(AFTER_LISTENER); }); } @@ -199,32 +182,22 @@ public class TaskListenerExecutorObjectFactoryTests { @Test public void verifyAllListenerWithMultipleInstances() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TaskExecutionListenerMultipleInstanceConfiguration.class); + .withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class); applicationContextRunner.run((context) -> { setup(context); - this.taskListenerExecutor - .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); - this.taskListenerExecutor.onTaskFailed( - createSampleTaskExecution(FAIL_LISTENER), + this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER), new IllegalStateException("oops")); - this.taskListenerExecutor - .onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); + this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER)); assertThat(taskExecutionListenerResults.size()).isEqualTo(6); - assertThat(taskExecutionListenerResults.get(0).getTaskName()) - .isEqualTo(BEFORE_LISTENER); - assertThat(taskExecutionListenerResults.get(1).getTaskName()) - .isEqualTo(BEFORE_LISTENER); - assertThat(taskExecutionListenerResults.get(2).getTaskName()) - .isEqualTo(FAIL_LISTENER); - assertThat(taskExecutionListenerResults.get(3).getTaskName()) - .isEqualTo(FAIL_LISTENER); - assertThat(taskExecutionListenerResults.get(4).getTaskName()) - .isEqualTo(AFTER_LISTENER); - assertThat(taskExecutionListenerResults.get(5).getTaskName()) - .isEqualTo(AFTER_LISTENER); + assertThat(taskExecutionListenerResults.get(0).getTaskName()).isEqualTo(BEFORE_LISTENER); + assertThat(taskExecutionListenerResults.get(1).getTaskName()).isEqualTo(BEFORE_LISTENER); + assertThat(taskExecutionListenerResults.get(2).getTaskName()).isEqualTo(FAIL_LISTENER); + assertThat(taskExecutionListenerResults.get(3).getTaskName()).isEqualTo(FAIL_LISTENER); + assertThat(taskExecutionListenerResults.get(4).getTaskName()).isEqualTo(AFTER_LISTENER); + assertThat(taskExecutionListenerResults.get(5).getTaskName()).isEqualTo(AFTER_LISTENER); }); } @@ -241,8 +214,7 @@ public class TaskListenerExecutorObjectFactoryTests { private void validateSingleEventWithMultipleInstances(String event) { assertThat(taskExecutionListenerResults.size()).isEqualTo(2); - assertThat(taskExecutionListenerResults) - .allSatisfy(task -> assertThat(task.getTaskName()).isEqualTo(event)); + assertThat(taskExecutionListenerResults).allSatisfy(task -> assertThat(task.getTaskName()).isEqualTo(event)); } @Configuration @@ -267,26 +239,24 @@ public class TaskListenerExecutorObjectFactoryTests { public TaskRunComponent otherTaskRunComponent() { return new TaskRunComponent(); } + } public static class TaskRunComponent { @BeforeTask public void initBeforeListener(TaskExecution taskExecution) { - TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults - .add(taskExecution); + TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution); } @AfterTask public void initAfterListener(TaskExecution taskExecution) { - TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults - .add(taskExecution); + TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution); } @FailedTask public void initFailedListener(TaskExecution taskExecution, Throwable exception) { - TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults - .add(taskExecution); + TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution); } } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/micrometer/TaskObservationsTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/micrometer/TaskObservationsTests.java index 79baa513..1ccec9f8 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/micrometer/TaskObservationsTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/micrometer/TaskObservationsTests.java @@ -63,7 +63,8 @@ public class TaskObservationsTests { public void before() { this.simpleMeterRegistry = new SimpleMeterRegistry(); this.observationRegistry = TestObservationRegistry.create(); - ObservationHandler timerObservationHandler = new TimerObservationHandler(this.simpleMeterRegistry); + ObservationHandler timerObservationHandler = new TimerObservationHandler( + this.simpleMeterRegistry); this.observationRegistry.observationConfig().observationHandler(timerObservationHandler); this.taskObservations = new TaskObservations(this.observationRegistry, null, null); } @@ -86,9 +87,8 @@ public class TaskObservationsTests { verifyDefaultKeyValues(); TaskExecutionObservation.TASK_ACTIVE.getDefaultConvention(); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags("spring.cloud.task", - Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags("spring.cloud.task", Tags + .of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123"); } @@ -96,43 +96,35 @@ public class TaskObservationsTests { @Test public void defaultTaskTest() { - TaskExecution taskExecution = new TaskExecution(123L, 0, null, new Date(), - new Date(), null, new ArrayList<>(), null, null, null); + TaskExecution taskExecution = new TaskExecution(123L, 0, null, new Date(), new Date(), null, new ArrayList<>(), + null, null, null); // Start Task taskObservations.onTaskStartup(taskExecution); LongTaskTimer longTaskTimer = initializeBasicTest(UNKNOWN, "123"); - // Finish Task taskObservations.onTaskEnd(taskExecution); // Test Timer - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "0")); - - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, - Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags + .of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); verifyLongTaskTimerAfterStop(longTaskTimer, "unknown", "123"); @@ -153,25 +145,20 @@ public class TaskObservationsTests { taskExecution.setExitCode(1); taskObservations.onTaskEnd(taskExecution); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), "-1")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "1")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, - Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_FAILURE)); + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags + .of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_FAILURE)); verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123"); } @@ -204,37 +191,29 @@ public class TaskObservationsTests { verifyDefaultKeyValues(); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(), ORGANIZATION_NAME)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(), SPACE_ID)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(), SPACE_NAME)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(), APPLICATION_NAME)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(), APPLICATION_ID)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(), APPLICATION_VERSION)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), INSTANCE_INDEX)); // Test Timer - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72")); verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123"); @@ -243,14 +222,13 @@ public class TaskObservationsTests { @Test public void testCloudVariablesUninitialized() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - CloudConfigurationForDefaultValues.class)); + .withConfiguration(AutoConfigurations.of(CloudConfigurationForDefaultValues.class)); applicationContextRunner.run((context) -> { TaskObservationCloudKeyValues taskObservationCloudKeyValues = context - .getBean(TaskObservationCloudKeyValues.class); + .getBean(TaskObservationCloudKeyValues.class); - assertThat(taskObservationCloudKeyValues) - .as("taskObservationCloudKeyValues should not be null").isNotNull(); + assertThat(taskObservationCloudKeyValues).as("taskObservationCloudKeyValues should not be null") + .isNotNull(); this.taskObservations = new TaskObservations(this.observationRegistry, taskObservationCloudKeyValues, null); @@ -263,37 +241,29 @@ public class TaskObservationsTests { verifyDefaultKeyValues(); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(), "default")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(), UNKNOWN)); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), "0")); // Test Timer - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72")); verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123"); @@ -301,8 +271,8 @@ public class TaskObservationsTests { } private TaskExecution startupObservationForBasicTests(String taskName, long taskExecutionId) { - TaskExecution taskExecution = new TaskExecution(taskExecutionId, 0, taskName, new Date(), - new Date(), null, new ArrayList<>(), null, "-1", -1L); + TaskExecution taskExecution = new TaskExecution(taskExecutionId, 0, taskName, new Date(), new Date(), null, + new ArrayList<>(), null, "-1", -1L); // Start Task taskObservations.onTaskStartup(taskExecution); @@ -312,56 +282,52 @@ public class TaskObservationsTests { private LongTaskTimer initializeBasicTest(String taskName, String executionId) { // Test Long Task Timer while the task is running. LongTaskTimer longTaskTimer = simpleMeterRegistry - .find(TaskExecutionObservation.TASK_ACTIVE.getPrefix() + ".active").longTaskTimer(); + .find(TaskExecutionObservation.TASK_ACTIVE.getPrefix() + ".active").longTaskTimer(); System.out.println(simpleMeterRegistry.getMetersAsString()); - assertThat(longTaskTimer) - .withFailMessage("LongTask timer should be created on Task start") - .isNotNull(); + assertThat(longTaskTimer).withFailMessage("LongTask timer should be created on Task start").isNotNull(); assertThat(longTaskTimer.activeTasks()).isEqualTo(1); assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName())) - .isEqualTo(taskName); + .isEqualTo(taskName); assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName())) - .isEqualTo(executionId); + .isEqualTo(executionId); return longTaskTimer; } private void verifyDefaultKeyValues() { // Test Timer - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), "-1")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "0")); - MeterRegistryAssert.assertThat(this.simpleMeterRegistry) - .hasTimerWithNameAndTags(PREFIX, - Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); + MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags + .of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS)); } private void verifyLongTaskTimerAfterStop(LongTaskTimer longTaskTimer, String taskName, String executionId) { // Test Long Task Timer after the task has completed. assertThat(longTaskTimer.activeTasks()).isEqualTo(0); assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName())) - .isEqualTo(taskName); + .isEqualTo(taskName); assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName())) - .isEqualTo(executionId); + .isEqualTo(executionId); } @Configuration static class CloudConfigurationForDefaultValues { + @Bean public TaskObservationCloudKeyValues taskObservationCloudKeyValues() { return new TaskObservationCloudKeyValues(); } + } + } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/H2TaskRepositoryIntegrationTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/H2TaskRepositoryIntegrationTests.java index 81ac644e..1227bcb2 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/H2TaskRepositoryIntegrationTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/H2TaskRepositoryIntegrationTests.java @@ -42,9 +42,8 @@ class H2TaskRepositoryIntegrationTests { void testTaskRepository(ModeEnum mode) { String connectionUrl = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;MODE=%s", UUID.randomUUID(), mode); ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class) - .withBean(DataSource.class, - () -> new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", "")); + .withUserConfiguration(TestConfiguration.class).withBean(DataSource.class, + () -> new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", "")); applicationContextRunner.run((context -> { TaskExplorer taskExplorer = context.getBean(TaskExplorer.class); @@ -55,6 +54,7 @@ class H2TaskRepositoryIntegrationTests { @EnableTask @ImportAutoConfiguration(SimpleTaskAutoConfiguration.class) static class TestConfiguration { + } } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/BaseTaskExecutionDaoTestCases.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/BaseTaskExecutionDaoTestCases.java index 109b3d9d..bb00b7a0 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/BaseTaskExecutionDaoTestCases.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/BaseTaskExecutionDaoTestCases.java @@ -46,8 +46,7 @@ public abstract class BaseTaskExecutionDaoTestCases { this.dao.getLatestTaskExecutionsByTaskNames(null); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()) - .isEqualTo("At least 1 task name must be provided."); + assertThat(e.getMessage()).isEqualTo("At least 1 task name must be provided."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -60,8 +59,7 @@ public abstract class BaseTaskExecutionDaoTestCases { this.dao.getLatestTaskExecutionsByTaskNames(new String[0]); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()) - .isEqualTo("At least 1 task name must be provided."); + assertThat(e.getMessage()).isEqualTo("At least 1 task name must be provided."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -74,8 +72,8 @@ public abstract class BaseTaskExecutionDaoTestCases { this.dao.getLatestTaskExecutionsByTaskNames("foo", null, "bar", " "); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo( - "Task names must not contain any empty elements but 2 of 4 were empty or null."); + assertThat(e.getMessage()) + .isEqualTo("Task names must not contain any empty elements but 2 of 4 were empty or null."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -85,11 +83,9 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionsByTaskNamesWithSingleTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = this.dao - .getLatestTaskExecutionsByTaskNames("FOO1"); - assertThat(latestTaskExecutions.size() == 1).as( - "Expected only 1 taskExecution but got " + latestTaskExecutions.size()) - .isTrue(); + final List latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO1"); + assertThat(latestTaskExecutions.size() == 1) + .as("Expected only 1 taskExecution but got " + latestTaskExecutions.size()).isTrue(); final TaskExecution lastTaskExecution = latestTaskExecutions.get(0); assertThat(lastTaskExecution.getTaskName()).isEqualTo("FOO1"); @@ -109,11 +105,10 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionsByTaskNamesWithMultipleTaskNames() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = this.dao - .getLatestTaskExecutionsByTaskNames("FOO1", "FOO3", "FOO4"); + final List latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO1", "FOO3", + "FOO4"); assertThat(latestTaskExecutions.size() == 3) - .as("Expected 3 taskExecutions but got " + latestTaskExecutions.size()) - .isTrue(); + .as("Expected 3 taskExecutions but got " + latestTaskExecutions.size()).isTrue(); final Calendar dateTimeFoo3 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTimeFoo3.setTime(latestTaskExecutions.get(0).getStartTime()); @@ -155,11 +150,9 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionsByTaskNamesWithIdenticalTaskExecutions() { long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = this.dao - .getLatestTaskExecutionsByTaskNames("FOO5"); - assertThat(latestTaskExecutions.size() == 1).as( - "Expected only 1 taskExecution but got " + latestTaskExecutions.size()) - .isTrue(); + final List latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO5"); + assertThat(latestTaskExecutions.size() == 1) + .as("Expected only 1 taskExecution but got " + latestTaskExecutions.size()).isTrue(); final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTime.setTime(latestTaskExecutions.get(0).getStartTime()); @@ -170,8 +163,7 @@ public abstract class BaseTaskExecutionDaoTestCases { assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23); assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59); assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0); - assertThat(latestTaskExecutions.get(0).getExecutionId()) - .isEqualTo(9 + executionIdOffset); + assertThat(latestTaskExecutions.get(0).getExecutionId()).isEqualTo(9 + executionIdOffset); } @Test @@ -204,11 +196,8 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionForNonExistingTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = this.dao - .getLatestTaskExecutionForTaskName("Bar5"); - assertThat(latestTaskExecution) - .as("Expected the latestTaskExecution to be null but got" - + latestTaskExecution) + final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("Bar5"); + assertThat(latestTaskExecution).as("Expected the latestTaskExecution to be null but got" + latestTaskExecution) .isNull(); } @@ -216,10 +205,8 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionForExistingTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = this.dao - .getLatestTaskExecutionForTaskName("FOO1"); - assertThat(latestTaskExecution) - .as("Expected the latestTaskExecution not to be null").isNotNull(); + final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("FOO1"); + assertThat(latestTaskExecution).as("Expected the latestTaskExecution not to be null").isNotNull(); final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTime.setTime(latestTaskExecution.getStartTime()); @@ -241,10 +228,8 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getLatestTaskExecutionForTaskNameWithIdenticalTaskExecutions() { long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = this.dao - .getLatestTaskExecutionForTaskName("FOO5"); - assertThat(latestTaskExecution) - .as("Expected the latestTaskExecution not to be null").isNotNull(); + final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("FOO5"); + assertThat(latestTaskExecution).as("Expected the latestTaskExecution not to be null").isNotNull(); final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTime.setTime(latestTaskExecution.getStartTime()); @@ -262,11 +247,9 @@ public abstract class BaseTaskExecutionDaoTestCases { @DirtiesContext public void getRunningTaskExecutions() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - assertThat(this.dao.getRunningTaskExecutionCount()) - .isEqualTo(this.dao.getTaskExecutionCount()); + assertThat(this.dao.getRunningTaskExecutionCount()).isEqualTo(this.dao.getTaskExecutionCount()); this.dao.completeTaskExecution(1, 0, new Date(), "c'est fini!"); - assertThat(this.dao.getRunningTaskExecutionCount()) - .isEqualTo(this.dao.getTaskExecutionCount() - 1); + assertThat(this.dao.getRunningTaskExecutionCount()).isEqualTo(this.dao.getTaskExecutionCount() - 1); } protected long initializeRepositoryNotInOrderWithMultipleTaskExecutions() { @@ -325,12 +308,11 @@ public abstract class BaseTaskExecutionDaoTestCases { } private long createTaskExecution(TaskExecution te) { - return this.dao.createTaskExecution(te.getTaskName(), te.getStartTime(), - te.getArguments(), te.getExternalExecutionId()).getExecutionId(); + return this.dao.createTaskExecution(te.getTaskName(), te.getStartTime(), te.getArguments(), + te.getExternalExecutionId()).getExecutionId(); } - protected TaskExecution getTaskExecution(String taskName, - String externalExecutionId) { + protected TaskExecution getTaskExecution(String taskName, String externalExecutionId) { TaskExecution taskExecution = new TaskExecution(); taskExecution.setTaskName(taskName); taskExecution.setExternalExecutionId(externalExecutionId); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDaoTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDaoTests.java index c8438496..48228821 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDaoTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDaoTests.java @@ -56,9 +56,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; * @author Michael Minella */ @ExtendWith(SpringExtension.class) -@ContextConfiguration( - classes = { TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ContextConfiguration(classes = { TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Autowired @@ -77,65 +76,52 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test @DirtiesContext public void testStartTaskExecution() { - TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, - new ArrayList<>(0), null); + TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null); - expectedTaskExecution.setArguments( - Collections.singletonList("foo=" + UUID.randomUUID().toString())); + expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString())); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void createTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - expectedTaskExecution = this.dao.createTaskExecution( - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void createEmptyTaskExecution() { - TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, - new ArrayList<>(0), null); + TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void completeTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .endSampleTaskExecutionNoArg(); - expectedTaskExecution = this.dao.createTaskExecution( - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage()); + this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), + expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @@ -143,13 +129,10 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { public void completeTaskExecutionWithNoCreate() { JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(this.dataSource); - TaskExecution expectedTaskExecution = TestVerifierUtils - .endSampleTaskExecutionNoArg(); + TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg(); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> { - dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), - expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage()); + dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), + expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); }); } @@ -189,12 +172,10 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { public void testStartExecutionWithNullExternalExecutionIdExisting() { TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), null); + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), null); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @@ -202,50 +183,48 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { public void testStartExecutionWithNullExternalExecutionIdNonExisting() { TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), "BAR"); + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "BAR"); expectedTaskExecution.setExternalExecutionId("BAR"); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void testFindRunningTaskExecutions() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - assertThat(this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("START_TIME"))).getTotalElements()) - .isEqualTo(4); + assertThat( + this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("START_TIME"))) + .getTotalElements()).isEqualTo(4); } @Test @DirtiesContext public void testFindRunningTaskExecutionsIllegalSort() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - assertThatThrownBy(() -> this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("ILLEGAL_SORT"))).getTotalElements()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid sort option selected: ILLEGAL_SORT"); + assertThatThrownBy(() -> this.dao + .findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("ILLEGAL_SORT"))) + .getTotalElements()).isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid sort option selected: ILLEGAL_SORT"); } @Test @DirtiesContext public void testFindRunningTaskExecutionsSortWithDifferentCase() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - assertThat(this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("StArT_TiMe"))).getTotalElements()) - .isEqualTo(4); + assertThat( + this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("StArT_TiMe"))) + .getTotalElements()).isEqualTo(4); } private TaskExecution initializeTaskExecutionWithExternalExecutionId() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "FOO1"); } - private Iterator getPageIterator(int pageNum, int pageSize, - Sort sort) { + private Iterator getPageIterator(int pageNum, int pageSize, Sort sort) { Pageable pageable = (sort == null) ? PageRequest.of(pageNum, pageSize) : PageRequest.of(pageNum, pageSize, sort); Page page = this.dao.findAll(pageable); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDaoTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDaoTests.java index 415e783b..8535d528 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDaoTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/MapTaskExecutionDaoTests.java @@ -52,20 +52,16 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test public void testStartTaskExecution() { - TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, - new ArrayList<>(0), null); + TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null); - expectedTaskExecution.setArguments( - Collections.singletonList("foo=" + UUID.randomUUID().toString())); + expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString())); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); @@ -73,37 +69,29 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test public void createEmptyTaskExecution() { - TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, - new ArrayList<>(0), null); + TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @Test public void completeTaskExecutionWithNoCreate() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> { - this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), - expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage()); + this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), + expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); }); } @Test public void saveTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - expectedTaskExecution = this.dao.createTaskExecution( - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); @@ -111,17 +99,13 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test public void completeTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - expectedTaskExecution = this.dao.createTaskExecution( - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage()); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); + this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), + expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); @@ -134,37 +118,31 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); for (TaskExecution expectedTaskExecution : expectedTaskExecutionList) { - expectedTaskExecution = this.dao.createTaskExecution( - expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), - expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage()); + this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), + expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); } Set jobIds = new HashSet<>(2); jobIds.add(123L); jobIds.add(456L); - this.mapTaskExecutionDao.getBatchJobAssociations() - .put(expectedTaskExecutionList.get(0).getExecutionId(), jobIds); + this.mapTaskExecutionDao.getBatchJobAssociations().put(expectedTaskExecutionList.get(0).getExecutionId(), + jobIds); - assertThat(this.dao.getTaskExecutionIdByJobExecutionId(123L)).isEqualTo( - Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId())); - assertThat(this.dao.getTaskExecutionIdByJobExecutionId(456L)).isEqualTo( - Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId())); + assertThat(this.dao.getTaskExecutionIdByJobExecutionId(123L)) + .isEqualTo(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId())); + assertThat(this.dao.getTaskExecutionIdByJobExecutionId(456L)) + .isEqualTo(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId())); assertThat(this.dao.getTaskExecutionIdByJobExecutionId(789L)).isNull(); } @Test public void testStartExecutionWithNullExternalExecutionIdExisting() { TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), null); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), null); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @@ -172,20 +150,16 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test public void testStartExecutionWithNullExternalExecutionIdNonExisting() { TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - Map taskExecutionMap = this.mapTaskExecutionDao - .getTaskExecutions(); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), "BAR"); + Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "BAR"); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } private TaskExecution initializeTaskExecutionWithExternalExecutionId() { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "FOO1"); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/FindAllPagingQueryProviderTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/FindAllPagingQueryProviderTests.java index a4802014..9345493e 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/FindAllPagingQueryProviderTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/FindAllPagingQueryProviderTests.java @@ -37,16 +37,14 @@ public class FindAllPagingQueryProviderTests { private Pageable pageable = PageRequest.of(0, 10); public static Collection data() { - return Arrays.asList(new Object[][] { - { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as " - + "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, " - + "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID " - + "FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, " - + "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " - + "TMP_ROW_NUM < 11" }, + return Arrays.asList(new Object[][] { { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as " + + "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, " + + "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID " + + "FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, " + + "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " + "TMP_ROW_NUM < 11" }, { "HSQL Database Engine", "SELECT LIMIT 0 10 TASK_EXECUTION_ID, " + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, " + "ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY " @@ -57,37 +55,31 @@ public class FindAllPagingQueryProviderTests { + "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0" }, { "MySQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "%PREFIX%EXECUTION ORDER BY START_TIME DESC, " - + "TASK_EXECUTION_ID DESC LIMIT 0, 10" }, - { "Microsoft SQL Server", - "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " - + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " - + "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS " - + "TMP_ROW_NUM FROM %PREFIX%EXECUTION) TASK_EXECUTION_PAGE " - + "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, " - + "TASK_EXECUTION_ID DESC" }, - { "DB2/Linux", - "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " - + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " - + "OVER() as TMP_ROW_NUM FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, " - + "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC)) " - + "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11"}}); + + "%PREFIX%EXECUTION ORDER BY START_TIME DESC, " + "TASK_EXECUTION_ID DESC LIMIT 0, 10" }, + { "Microsoft SQL Server", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " + + "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS " + + "TMP_ROW_NUM FROM %PREFIX%EXECUTION) TASK_EXECUTION_PAGE " + + "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, " + + "TASK_EXECUTION_ID DESC" }, + { "DB2/Linux", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " + + "OVER() as TMP_ROW_NUM FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, " + + "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC)) " + + "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11" } }); } @ParameterizedTest @MethodSource("data") - public void testGeneratedQuery(String databaseProductName, String expectedQuery) - throws Exception { - String actualQuery = TestDBUtils.getPagingQueryProvider(databaseProductName) - .getPageQuery(this.pageable); - assertThat(actualQuery).as( - String.format("the generated query for %s, was not the expected query", - databaseProductName)) + public void testGeneratedQuery(String databaseProductName, String expectedQuery) throws Exception { + String actualQuery = TestDBUtils.getPagingQueryProvider(databaseProductName).getPageQuery(this.pageable); + assertThat(actualQuery) + .as(String.format("the generated query for %s, was not the expected query", databaseProductName)) .isEqualTo(expectedQuery); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProviderTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProviderTests.java index 68347857..b35f3344 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProviderTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/H2PagingQueryProviderTests.java @@ -64,16 +64,12 @@ class H2PagingQueryProviderTests { sortKeys.put("ID", Order.ASCENDING); queryProvider.setSortKeys(sortKeys); - List firstPage = jdbcTemplate.queryForList( - queryProvider.getPageQuery(PageRequest.of(0, 2)), - String.class - ); + List firstPage = jdbcTemplate.queryForList(queryProvider.getPageQuery(PageRequest.of(0, 2)), + String.class); assertThat(firstPage).containsExactly("Spring", "Cloud"); - List secondPage = jdbcTemplate.queryForList( - queryProvider.getPageQuery(PageRequest.of(1, 2)), - String.class - ); + List secondPage = jdbcTemplate.queryForList(queryProvider.getPageQuery(PageRequest.of(1, 2)), + String.class); assertThat(secondPage).containsExactly("Task"); }); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/WhereClausePagingQueryProviderTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/WhereClausePagingQueryProviderTests.java index 6535494f..686ebe45 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/WhereClausePagingQueryProviderTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/WhereClausePagingQueryProviderTests.java @@ -37,53 +37,45 @@ public class WhereClausePagingQueryProviderTests { private Pageable pageable = PageRequest.of(0, 10); public static Collection data() { - return Arrays.asList(new Object[][] { - { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as " - + "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, " - + "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, " - + "LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION " - + "WHERE TASK_EXECUTION_ID = '0000' ORDER BY START_TIME DESC, " - + "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " - + "TMP_ROW_NUM < 11" }, + return Arrays.asList(new Object[][] { { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as " + + "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, " + + "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, " + + "LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION " + + "WHERE TASK_EXECUTION_ID = '0000' ORDER BY START_TIME DESC, " + + "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " + "TMP_ROW_NUM < 11" }, { "HSQL Database Engine", "SELECT LIMIT 0 10 TASK_EXECUTION_ID, " + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, " + "ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION " - + "WHERE TASK_EXECUTION_ID = '0000' ORDER BY " - + "START_TIME DESC, TASK_EXECUTION_ID DESC" }, + + "WHERE TASK_EXECUTION_ID = '0000' ORDER BY " + "START_TIME DESC, TASK_EXECUTION_ID DESC" }, { "PostgreSQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID " - + "FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " - + "ORDER BY START_TIME DESC, " + + "FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " + "ORDER BY START_TIME DESC, " + "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0" }, { "MySQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " - + "ORDER BY START_TIME DESC, " + + "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " + "ORDER BY START_TIME DESC, " + "TASK_EXECUTION_ID DESC LIMIT 0, 10" }, - { "Microsoft SQL Server", - "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " - + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " - + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " - + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " - + "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS " - + "TMP_ROW_NUM FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = " - + "'0000') TASK_EXECUTION_PAGE WHERE TMP_ROW_NUM >= 1 " - + "AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC" } }); + { "Microsoft SQL Server", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + + "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM " + + "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() " + + "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS " + + "TMP_ROW_NUM FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = " + + "'0000') TASK_EXECUTION_PAGE WHERE TMP_ROW_NUM >= 1 " + + "AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC" } }); } @ParameterizedTest @MethodSource("data") - public void testGeneratedQuery(String databaseProductName, String expectedQuery) - throws Exception { - PagingQueryProvider pagingQueryProvider = TestDBUtils.getPagingQueryProvider( - databaseProductName, "TASK_EXECUTION_ID = '0000'"); + public void testGeneratedQuery(String databaseProductName, String expectedQuery) throws Exception { + PagingQueryProvider pagingQueryProvider = TestDBUtils.getPagingQueryProvider(databaseProductName, + "TASK_EXECUTION_ID = '0000'"); String actualQuery = pagingQueryProvider.getPageQuery(this.pageable); - assertThat(actualQuery).as( - String.format("the generated query for %s, was not the expected query", - databaseProductName)) + assertThat(actualQuery) + .as(String.format("the generated query for %s, was not the expected query", databaseProductName)) .isEqualTo(expectedQuery); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/DatabaseTypeTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/DatabaseTypeTests.java index 0cee6515..b02bc89b 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/DatabaseTypeTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/DatabaseTypeTests.java @@ -51,8 +51,7 @@ public class DatabaseTypeTests { @Test public void testInvalidProductName() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> fromProductName("bad product name")); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> fromProductName("bad product name")); } @Test diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorerTests.java index de2dd71d..e959dd21 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskExplorerTests.java @@ -94,13 +94,10 @@ public class SimpleTaskExplorerTests { testDefaultContext(testType); Map expectedResults = createSampleDataSet(5); for (Long taskExecutionId : expectedResults.keySet()) { - TaskExecution actualTaskExecution = this.taskExplorer - .getTaskExecution(taskExecutionId); - assertThat(actualTaskExecution).as(String.format( - "expected a taskExecution but got null for test type %s", testType)) - .isNotNull(); - TestVerifierUtils.verifyTaskExecution(expectedResults.get(taskExecutionId), - actualTaskExecution); + TaskExecution actualTaskExecution = this.taskExplorer.getTaskExecution(taskExecutionId); + assertThat(actualTaskExecution) + .as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull(); + TestVerifierUtils.verifyTaskExecution(expectedResults.get(taskExecutionId), actualTaskExecution); } } @@ -111,8 +108,7 @@ public class SimpleTaskExplorerTests { createSampleDataSet(5); TaskExecution actualTaskExecution = this.taskExplorer.getTaskExecution(-5); - assertThat(actualTaskExecution) - .as(String.format("expected null for actualTaskExecution %s", testType)) + assertThat(actualTaskExecution).as(String.format("expected null for actualTaskExecution %s", testType)) .isNull(); } @@ -123,10 +119,8 @@ public class SimpleTaskExplorerTests { Map expectedResults = createSampleDataSet(5); for (Map.Entry entry : expectedResults.entrySet()) { String taskName = entry.getValue().getTaskName(); - assertThat(this.taskExplorer.getTaskExecutionCountByTaskName(taskName)) - .as(String.format( - "task count for task name did not match expected result for testType %s", - testType)) + assertThat(this.taskExplorer.getTaskExecutionCountByTaskName(taskName)).as( + String.format("task count for task name did not match expected result for testType %s", testType)) .isEqualTo(1); } } @@ -136,9 +130,8 @@ public class SimpleTaskExplorerTests { public void getTaskCount(DaoType testType) { testDefaultContext(testType); createSampleDataSet(33); - assertThat(this.taskExplorer.getTaskExecutionCount()).as(String.format( - "task count did not match expected result for test Type %s", testType)) - .isEqualTo(33); + assertThat(this.taskExplorer.getTaskExecutionCount()) + .as(String.format("task count did not match expected result for test Type %s", testType)).isEqualTo(33); } @ParameterizedTest @@ -146,9 +139,8 @@ public class SimpleTaskExplorerTests { public void getRunningTaskCount(DaoType testType) { testDefaultContext(testType); createSampleDataSet(33); - assertThat(this.taskExplorer.getRunningTaskExecutionCount()).as(String.format( - "task count did not match expected result for test Type %s", testType)) - .isEqualTo(33); + assertThat(this.taskExplorer.getRunningTaskExecutionCount()) + .as(String.format("task count did not match expected result for test Type %s", testType)).isEqualTo(33); } @ParameterizedTest @@ -166,27 +158,23 @@ public class SimpleTaskExplorerTests { } for (; i < (COMPLETE_COUNT + TEST_COUNT); i++) { - TaskExecution expectedTaskExecution = this.taskRepository - .createTaskExecution(getSimpleTaskExecution()); - expectedResults.put(expectedTaskExecution.getExecutionId(), - expectedTaskExecution); + TaskExecution expectedTaskExecution = this.taskRepository.createTaskExecution(getSimpleTaskExecution()); + expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution); } Pageable pageable = PageRequest.of(0, 10); - Page actualResults = this.taskExplorer - .findRunningTaskExecutions(TASK_NAME, pageable); - assertThat(actualResults.getNumberOfElements()).as(String.format( - "Running task count for task name did not match expected result for testType %s", - testType)).isEqualTo(TEST_COUNT); + Page actualResults = this.taskExplorer.findRunningTaskExecutions(TASK_NAME, pageable); + assertThat(actualResults.getNumberOfElements()).as(String + .format("Running task count for task name did not match expected result for testType %s", testType)) + .isEqualTo(TEST_COUNT); for (TaskExecution result : actualResults) { - assertThat(expectedResults.containsKey(result.getExecutionId())).as(String - .format("result returned from repo %s not expected for testType %s", + assertThat(expectedResults.containsKey(result.getExecutionId())) + .as(String.format("result returned from repo %s not expected for testType %s", result.getExecutionId(), testType)) .isTrue(); - assertThat(result.getEndTime()).as(String.format( - "result had non null for endTime for the testType %s", testType)) - .isNull(); + assertThat(result.getEndTime()) + .as(String.format("result had non null for endTime for the testType %s", testType)).isNull(); } } @@ -204,26 +192,22 @@ public class SimpleTaskExplorerTests { } for (int i = 0; i < TEST_COUNT; i++) { - TaskExecution expectedTaskExecution = this.taskRepository - .createTaskExecution(getSimpleTaskExecution()); - expectedResults.put(expectedTaskExecution.getExecutionId(), - expectedTaskExecution); + TaskExecution expectedTaskExecution = this.taskRepository.createTaskExecution(getSimpleTaskExecution()); + expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution); } Pageable pageable = PageRequest.of(0, 10); - Page resultSet = this.taskExplorer - .findTaskExecutionsByName(TASK_NAME, pageable); - assertThat(resultSet.getNumberOfElements()).as(String.format( - "Running task count for task name did not match expected result for testType %s", - testType)).isEqualTo(TEST_COUNT); + Page resultSet = this.taskExplorer.findTaskExecutionsByName(TASK_NAME, pageable); + assertThat(resultSet.getNumberOfElements()).as(String + .format("Running task count for task name did not match expected result for testType %s", testType)) + .isEqualTo(TEST_COUNT); for (TaskExecution result : resultSet) { - assertThat(expectedResults.containsKey(result.getExecutionId())) - .as(String.format("result returned from %s repo %s not expected", - testType, result.getExecutionId())) + assertThat(expectedResults.containsKey(result.getExecutionId())).as( + String.format("result returned from %s repo %s not expected", testType, result.getExecutionId())) .isTrue(); - assertThat(result.getTaskName()).as(String.format( - "taskName for taskExecution is incorrect for testType %s", testType)) + assertThat(result.getTaskName()) + .as(String.format("taskName for taskExecution is incorrect for testType %s", testType)) .isEqualTo(TASK_NAME); } } @@ -240,9 +224,8 @@ public class SimpleTaskExplorerTests { } List actualTaskNames = this.taskExplorer.getTaskNames(); for (String taskName : actualTaskNames) { - assertThat(expectedResults.contains(taskName)).as(String.format( - "taskName was not in expected results for testType %s", testType)) - .isTrue(); + assertThat(expectedResults.contains(taskName)) + .as(String.format("taskName was not in expected results for testType %s", testType)).isTrue(); } } @@ -289,8 +272,7 @@ public class SimpleTaskExplorerTests { @MethodSource("data") public void findJobsExecutionIdsForInvalidTask(DaoType testType) { testDefaultContext(testType); - assertThat(this.taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size()) - .isEqualTo(0); + assertThat(this.taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size()).isEqualTo(0); } @ParameterizedTest @@ -298,16 +280,12 @@ public class SimpleTaskExplorerTests { public void getLatestTaskExecutionForTaskName(DaoType testType) { testDefaultContext(testType); Map expectedResults = createSampleDataSet(5); - for (Map.Entry taskExecutionMapEntry : expectedResults - .entrySet()) { + for (Map.Entry taskExecutionMapEntry : expectedResults.entrySet()) { TaskExecution latestTaskExecution = this.taskExplorer - .getLatestTaskExecutionForTaskName( - taskExecutionMapEntry.getValue().getTaskName()); - assertThat(latestTaskExecution).as(String.format( - "expected a taskExecution but got null for test type %s", testType)) - .isNotNull(); - TestVerifierUtils.verifyTaskExecution( - expectedResults.get(latestTaskExecution.getExecutionId()), + .getLatestTaskExecutionForTaskName(taskExecutionMapEntry.getValue().getTaskName()); + assertThat(latestTaskExecution) + .as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull(); + TestVerifierUtils.verifyTaskExecution(expectedResults.get(latestTaskExecution.getExecutionId()), latestTaskExecution); } } @@ -325,33 +303,26 @@ public class SimpleTaskExplorerTests { } final List latestTaskExecutions = this.taskExplorer - .getLatestTaskExecutionsByTaskNames( - taskNamesAsList.toArray(new String[taskNamesAsList.size()])); + .getLatestTaskExecutionsByTaskNames(taskNamesAsList.toArray(new String[taskNamesAsList.size()])); for (TaskExecution latestTaskExecution : latestTaskExecutions) { - assertThat(latestTaskExecution).as(String.format( - "expected a taskExecution but got null for test type %s", testType)) - .isNotNull(); - TestVerifierUtils.verifyTaskExecution( - expectedResults.get(latestTaskExecution.getExecutionId()), + assertThat(latestTaskExecution) + .as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull(); + TestVerifierUtils.verifyTaskExecution(expectedResults.get(latestTaskExecution.getExecutionId()), latestTaskExecution); } } private void verifyPageResults(Pageable pageable, int totalNumberOfExecs) { - Map expectedResults = createSampleDataSet( - totalNumberOfExecs); + Map expectedResults = createSampleDataSet(totalNumberOfExecs); List sortedExecIds = getSortedOfTaskExecIds(expectedResults); Iterator expectedTaskExecutionIter = sortedExecIds.iterator(); // Verify pageable totals Page taskPage = this.taskExplorer.findAll(pageable); - int pagesExpected = (int) Math - .ceil(totalNumberOfExecs / ((double) pageable.getPageSize())); - assertThat(taskPage.getTotalPages()) - .as("actual page count return was not the expected total") + int pagesExpected = (int) Math.ceil(totalNumberOfExecs / ((double) pageable.getPageSize())); + assertThat(taskPage.getTotalPages()).as("actual page count return was not the expected total") .isEqualTo(pagesExpected); - assertThat(taskPage.getTotalElements()) - .as("actual element count was not the expected count") + assertThat(taskPage.getTotalElements()).as("actual element count was not the expected count") .isEqualTo(totalNumberOfExecs); // Verify pagination @@ -367,16 +338,14 @@ public class SimpleTaskExplorerTests { if (!hasMorePages && pageable.getPageSize() != actualTaskExecutions.size()) { expectedPageSize = totalNumberOfExecs % pageable.getPageSize(); } - assertThat(actualTaskExecutions.size()).as(String.format( - "Element count on page did not match on the %n page", pageNumber)) + assertThat(actualTaskExecutions.size()) + .as(String.format("Element count on page did not match on the %n page", pageNumber)) .isEqualTo(expectedPageSize); for (TaskExecution actualExecution : actualTaskExecutions) { assertThat(actualExecution.getExecutionId()) - .as(String.format("Element on page %n did not match expected", - pageNumber)) + .as(String.format("Element on page %n did not match expected", pageNumber)) .isEqualTo((long) expectedTaskExecutionIter.next()); - TestVerifierUtils.verifyTaskExecution( - expectedResults.get(actualExecution.getExecutionId()), + TestVerifierUtils.verifyTaskExecution(expectedResults.get(actualExecution.getExecutionId()), actualExecution); elementCount++; } @@ -384,10 +353,8 @@ public class SimpleTaskExplorerTests { pageNumber++; } // Verify actual totals - assertThat(pageNumber).as("Pages processed did not equal expected") - .isEqualTo(pagesExpected); - assertThat(elementCount).as("Elements processed did not equal expected,") - .isEqualTo(totalNumberOfExecs); + assertThat(pageNumber).as("Pages processed did not equal expected").isEqualTo(pagesExpected); + assertThat(elementCount).as("Elements processed did not equal expected,").isEqualTo(totalNumberOfExecs); } private TaskExecution createAndSaveTaskExecution(int i) { @@ -398,8 +365,7 @@ public class SimpleTaskExplorerTests { private void initializeJdbcExplorerTest() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); @@ -409,8 +375,7 @@ public class SimpleTaskExplorerTests { private void initializeMapExplorerTest() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.context.getAutowireCapableBeanFactory().autowireBeanProperties(this, @@ -421,8 +386,7 @@ public class SimpleTaskExplorerTests { Map expectedResults = new HashMap<>(); for (int i = 0; i < count; i++) { TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i); - expectedResults.put(expectedTaskExecution.getExecutionId(), - expectedTaskExecution); + expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution); } return expectedResults; } @@ -444,8 +408,7 @@ public class SimpleTaskExplorerTests { public int compare(TaskExecution e1, TaskExecution e2) { int result = e1.getStartTime().compareTo(e2.getStartTime()); if (result == 0) { - result = Long.valueOf(e1.getExecutionId()) - .compareTo(e2.getExecutionId()); + result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId()); } return result; } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolverTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolverTests.java index e75298c6..5359642b 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolverTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskNameResolverTests.java @@ -34,9 +34,8 @@ public class SimpleTaskNameResolverTests { SimpleTaskNameResolver taskNameResolver = new SimpleTaskNameResolver(); taskNameResolver.setApplicationContext(context); - assertThat(taskNameResolver.getTaskName().startsWith( - "org.springframework.context.support.GenericApplicationContext")) - .isTrue(); + assertThat(taskNameResolver.getTaskName() + .startsWith("org.springframework.context.support.GenericApplicationContext")).isTrue(); } @Test diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryJdbcTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryJdbcTests.java index 987bbbd9..fb7213cc 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryJdbcTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryJdbcTests.java @@ -49,8 +49,8 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Ilayaperumal Gopinathan */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { EmbeddedDataSourceConfiguration.class, - SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) +@ContextConfiguration(classes = { EmbeddedDataSourceConfiguration.class, SimpleTaskAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext public class SimpleTaskRepositoryJdbcTests { @@ -65,8 +65,8 @@ public class SimpleTaskRepositoryJdbcTests { public void testCreateEmptyExecution() { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreEmptyTaskExecution(this.taskRepository); - TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( - this.dataSource, expectedTaskExecution.getExecutionId()); + TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -75,8 +75,8 @@ public class SimpleTaskRepositoryJdbcTests { public void testCreateTaskExecutionNoParam() { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); - TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( - this.dataSource, expectedTaskExecution.getExecutionId()); + TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -85,8 +85,8 @@ public class SimpleTaskRepositoryJdbcTests { public void testCreateTaskExecutionWithParam() { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionWithParams(this.taskRepository); - TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( - this.dataSource, expectedTaskExecution.getExecutionId()); + TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -96,15 +96,13 @@ public class SimpleTaskRepositoryJdbcTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreEmptyTaskExecution(this.taskRepository); - expectedTaskExecution.setArguments( - Collections.singletonList("foo=" + UUID.randomUUID().toString())); + expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString())); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); @@ -120,9 +118,8 @@ public class SimpleTaskRepositoryJdbcTests { expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); @@ -133,12 +130,10 @@ public class SimpleTaskRepositoryJdbcTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString()); - this.taskRepository.updateExternalExecutionId( - expectedTaskExecution.getExecutionId(), + this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @@ -146,12 +141,10 @@ public class SimpleTaskRepositoryJdbcTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - this.taskRepository.updateExternalExecutionId( - expectedTaskExecution.getExecutionId(), + this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(this.dataSource, - expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test @@ -160,8 +153,7 @@ public class SimpleTaskRepositoryJdbcTests { .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> { - this.taskRepository.updateExternalExecutionId(-1, - expectedTaskExecution.getExternalExecutionId()); + this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId()); }); } @@ -176,11 +168,9 @@ public class SimpleTaskRepositoryJdbcTests { expectedTaskExecution.setParentExecutionId(12345L); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), - expectedTaskExecution.getExternalExecutionId(), - expectedTaskExecution.getParentExecutionId()); + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId(), expectedTaskExecution.getParentExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -194,8 +184,8 @@ public class SimpleTaskRepositoryJdbcTests { expectedTaskExecution.setExitCode(77); expectedTaskExecution.setExitMessage(UUID.randomUUID().toString()); - TaskExecution actualTaskExecution = TaskExecutionCreator - .completeExecution(this.taskRepository, expectedTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository, + expectedTaskExecution); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -204,14 +194,11 @@ public class SimpleTaskRepositoryJdbcTests { public void testCreateTaskExecutionNoParamMaxExitDefaultMessageSize() { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); - expectedTaskExecution.setExitMessage( - new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); + expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, - this.taskRepository); - assertThat(actualTaskExecution.getExitMessage().length()) - .isEqualTo(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, this.taskRepository); + assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE); } @Test @@ -222,12 +209,10 @@ public class SimpleTaskRepositoryJdbcTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(simpleTaskRepository); - expectedTaskExecution.setExitMessage( - new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); + expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, - simpleTaskRepository); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository); assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(5); } @@ -236,12 +221,10 @@ public class SimpleTaskRepositoryJdbcTests { public void testCreateTaskExecutionNoParamMaxErrorDefaultMessageSize() { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); - expectedTaskExecution.setErrorMessage( - new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); + expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, - this.taskRepository); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, this.taskRepository); assertThat(actualTaskExecution.getErrorMessage().length()) .isEqualTo(SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE); } @@ -254,12 +237,10 @@ public class SimpleTaskRepositoryJdbcTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(simpleTaskRepository); - expectedTaskExecution.setErrorMessage( - new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); + expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, - simpleTaskRepository); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository); assertThat(actualTaskExecution.getErrorMessage().length()).isEqualTo(5); } @@ -269,10 +250,9 @@ public class SimpleTaskRepositoryJdbcTests { final int MAX_ERROR_MESSAGE_SIZE = 20; final int MAX_TASK_NAME_SIZE = 30; SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository( - new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, - MAX_TASK_NAME_SIZE, MAX_ERROR_MESSAGE_SIZE); - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); + new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, MAX_TASK_NAME_SIZE, + MAX_ERROR_MESSAGE_SIZE); + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); expectedTaskExecution.setTaskName(new String(new char[MAX_TASK_NAME_SIZE + 1])); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { simpleTaskRepository.createTaskExecution(expectedTaskExecution); @@ -283,10 +263,8 @@ public class SimpleTaskRepositoryJdbcTests { public void testDefaultMaxTaskNameSizeForConstructor() { SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository( new TaskExecutionDaoFactoryBean(this.dataSource), null, null, null); - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); - expectedTaskExecution.setTaskName( - new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1])); + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + expectedTaskExecution.setTaskName(new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1])); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { simpleTaskRepository.createTaskExecution(expectedTaskExecution); }); @@ -297,10 +275,8 @@ public class SimpleTaskRepositoryJdbcTests { final int MAX_EXIT_MESSAGE_SIZE = 10; final int MAX_ERROR_MESSAGE_SIZE = 20; SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository( - new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, - null, MAX_ERROR_MESSAGE_SIZE); - verifyTaskRepositoryConstructor(MAX_EXIT_MESSAGE_SIZE, MAX_ERROR_MESSAGE_SIZE, - simpleTaskRepository); + new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, null, MAX_ERROR_MESSAGE_SIZE); + verifyTaskRepositoryConstructor(MAX_EXIT_MESSAGE_SIZE, MAX_ERROR_MESSAGE_SIZE, simpleTaskRepository); } @Test @@ -315,8 +291,7 @@ public class SimpleTaskRepositoryJdbcTests { @DirtiesContext public void testCreateTaskExecutionNoParamMaxTaskName() { TaskExecution taskExecution = new TaskExecution(); - taskExecution.setTaskName( - new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1])); + taskExecution.setTaskName(new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1])); taskExecution.setStartTime(new Date()); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { this.taskRepository.createTaskExecution(taskExecution); @@ -332,10 +307,9 @@ public class SimpleTaskRepositoryJdbcTests { expectedTaskExecution.setExitCode(-1); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { - TaskExecution actualTaskExecution = TaskExecutionCreator - .completeExecution(this.taskRepository, expectedTaskExecution); - TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - actualTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository, + expectedTaskExecution); + TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); }); } @@ -346,35 +320,27 @@ public class SimpleTaskRepositoryJdbcTests { .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExitCode(-1); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { - TaskExecutionCreator.completeExecution(this.taskRepository, - expectedTaskExecution); + TaskExecutionCreator.completeExecution(this.taskRepository, expectedTaskExecution); }); } - private TaskExecution completeTaskExecution(TaskExecution expectedTaskExecution, - TaskRepository taskRepository) { - return taskRepository.completeTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getExitCode(), new Date(), - expectedTaskExecution.getExitMessage(), + private TaskExecution completeTaskExecution(TaskExecution expectedTaskExecution, TaskRepository taskRepository) { + return taskRepository.completeTaskExecution(expectedTaskExecution.getExecutionId(), + expectedTaskExecution.getExitCode(), new Date(), expectedTaskExecution.getExitMessage(), expectedTaskExecution.getErrorMessage()); } - private void verifyTaskRepositoryConstructor(Integer maxExitMessage, - Integer maxErrorMessage, TaskRepository taskRepository) { - TaskExecution expectedTaskExecution = TaskExecutionCreator - .createAndStoreTaskExecutionNoParams(taskRepository); + private void verifyTaskRepositoryConstructor(Integer maxExitMessage, Integer maxErrorMessage, + TaskRepository taskRepository) { + TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); expectedTaskExecution.setErrorMessage(new String(new char[maxErrorMessage + 1])); expectedTaskExecution.setExitMessage(new String(new char[maxExitMessage + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, - taskRepository); - assertThat(actualTaskExecution.getErrorMessage().length()) - .isEqualTo(maxErrorMessage.intValue()); - assertThat(actualTaskExecution.getExitMessage().length()) - .isEqualTo(maxExitMessage.intValue()); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, taskRepository); + assertThat(actualTaskExecution.getErrorMessage().length()).isEqualTo(maxErrorMessage.intValue()); + assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(maxExitMessage.intValue()); } } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryMapTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryMapTests.java index 2e3ebd8a..45318bce 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryMapTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SimpleTaskRepositoryMapTests.java @@ -53,8 +53,7 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreEmptyTaskExecution(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository( - expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); } @Test @@ -62,8 +61,7 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository( - expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); } @Test @@ -71,12 +69,10 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString()); - this.taskRepository.updateExternalExecutionId( - expectedTaskExecution.getExecutionId(), + this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository( - expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); } @Test @@ -84,12 +80,10 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - this.taskRepository.updateExternalExecutionId( - expectedTaskExecution.getExecutionId(), + this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository( - expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); } @Test @@ -98,8 +92,7 @@ public class SimpleTaskRepositoryMapTests { .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { - this.taskRepository.updateExternalExecutionId(-1, - expectedTaskExecution.getExternalExecutionId()); + this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId()); }); } @@ -108,8 +101,7 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreTaskExecutionWithParams(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository( - expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); } @Test @@ -117,17 +109,14 @@ public class SimpleTaskRepositoryMapTests { TaskExecution expectedTaskExecution = TaskExecutionCreator .createAndStoreEmptyTaskExecution(this.taskRepository); - expectedTaskExecution.setArguments( - Collections.singletonList("foo=" + UUID.randomUUID().toString())); + expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString())); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), - expectedTaskExecution.getExternalExecutionId(), - expectedTaskExecution.getParentExecutionId()); + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId(), expectedTaskExecution.getParentExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -141,9 +130,8 @@ public class SimpleTaskRepositoryMapTests { expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); @@ -159,9 +147,8 @@ public class SimpleTaskRepositoryMapTests { expectedTaskExecution.setParentExecutionId(12345L); TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( - expectedTaskExecution.getExecutionId(), - expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), + expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); @@ -173,16 +160,15 @@ public class SimpleTaskRepositoryMapTests { .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = TaskExecutionCreator - .completeExecution(this.taskRepository, expectedTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository, + expectedTaskExecution); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } private TaskExecution getSingleTaskExecutionFromMapRepository(long taskExecutionId) { Map taskMap = ((MapTaskExecutionDao) ((SimpleTaskRepository) this.taskRepository) .getTaskExecutionDao()).getTaskExecutions(); - assertTrue("taskExecutionId must be in MapTaskExecutionRepository", - taskMap.containsKey(taskExecutionId)); + assertTrue("taskExecutionId must be in MapTaskExecutionRepository", taskMap.containsKey(taskExecutionId)); return taskMap.get(taskExecutionId); } @@ -192,8 +178,7 @@ public class SimpleTaskRepositoryMapTests { .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExitCode(-1); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { - TaskExecutionCreator.completeExecution(this.taskRepository, - expectedTaskExecution); + TaskExecutionCreator.completeExecution(this.taskRepository, expectedTaskExecution); }); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementerTests.java index fa7afc36..1b47dac3 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/SqlServerSequenceMaxValueIncrementerTests.java @@ -40,7 +40,7 @@ public class SqlServerSequenceMaxValueIncrementerTests { @Test public void testDefaultDataSourceConfiguration() throws Exception { this.context = new AnnotationConfigApplicationContext( - TaskExecutionDaoFactoryBeanTests.DefaultDataSourceConfiguration.class); + TaskExecutionDaoFactoryBeanTests.DefaultDataSourceConfiguration.class); DataSource dataSource = this.context.getBean(DataSource.class); @@ -48,4 +48,5 @@ public class SqlServerSequenceMaxValueIncrementerTests { assertThat(incrementer.getSequenceQuery()).isEqualTo("select next value for foo"); assertThat(incrementer.getIncrementerName()).isEqualTo("foo"); } + } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskDatabaseInitializerTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskDatabaseInitializerTests.java index 3eb53b37..5616ab10 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskDatabaseInitializerTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskDatabaseInitializerTests.java @@ -54,21 +54,18 @@ public class TaskDatabaseInitializerTests { @Test public void testDefaultContext() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from TASK_EXECUTION").size()).isEqualTo(0); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)).queryForList("select * from TASK_EXECUTION") + .size()).isEqualTo(0); } @Test public void testNoDatabase() { this.context = new AnnotationConfigApplicationContext(EmptyConfiguration.class); - SimpleTaskRepository repository = new SimpleTaskRepository( - new TaskExecutionDaoFactoryBean()); - assertThat(repository.getTaskExecutionDao()) - .isInstanceOf(MapTaskExecutionDao.class); + SimpleTaskRepository repository = new SimpleTaskRepository(new TaskExecutionDaoFactoryBean()); + assertThat(repository.getTaskExecutionDao()).isInstanceOf(MapTaskExecutionDao.class); MapTaskExecutionDao dao = (MapTaskExecutionDao) repository.getTaskExecutionDao(); assertThat(dao.getTaskExecutions().size()).isEqualTo(0); } @@ -76,19 +73,16 @@ public class TaskDatabaseInitializerTests { @Test public void testNoTaskConfiguration() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(EmptyConfiguration.class, - EmbeddedDataSourceConfiguration.class, + this.context.register(EmptyConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SimpleTaskRepository.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(SimpleTaskRepository.class).length).isEqualTo(0); } @Test public void testMultipleDataSourcesContext() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(SimpleTaskAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class, + this.context.register(SimpleTaskAutoConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); DataSource dataSource = mock(DataSource.class); this.context.getBeanFactory().registerSingleton("mockDataSource", dataSource); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBeanTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBeanTests.java index 9ccca16a..465217c2 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBeanTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/support/TaskExecutionDaoFactoryBeanTests.java @@ -51,8 +51,7 @@ public class TaskExecutionDaoFactoryBeanTests { @Test public void testGetObjectType() { - assertThat(TaskExecutionDao.class) - .isEqualTo(new TaskExecutionDaoFactoryBean().getObjectType()); + assertThat(TaskExecutionDao.class).isEqualTo(new TaskExecutionDaoFactoryBean().getObjectType()); } @Test @@ -81,13 +80,11 @@ public class TaskExecutionDaoFactoryBeanTests { @Test public void testDefaultDataSourceConfiguration() throws Exception { - this.context = new AnnotationConfigApplicationContext( - DefaultDataSourceConfiguration.class); + this.context = new AnnotationConfigApplicationContext(DefaultDataSourceConfiguration.class); DataSource dataSource = this.context.getBean(DataSource.class); - TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean( - dataSource); + TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource); TaskExecutionDao taskExecutionDao = factoryBean.getObject(); assertThat(taskExecutionDao instanceof JdbcTaskExecutionDao).isTrue(); @@ -99,17 +96,14 @@ public class TaskExecutionDaoFactoryBeanTests { @Test public void testSettingTablePrefix() throws Exception { - this.context = new AnnotationConfigApplicationContext( - DefaultDataSourceConfiguration.class); + this.context = new AnnotationConfigApplicationContext(DefaultDataSourceConfiguration.class); DataSource dataSource = this.context.getBean(DataSource.class); - TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean( - dataSource, "foo_"); + TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource, "foo_"); TaskExecutionDao taskExecutionDao = factoryBean.getObject(); - assertThat(ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix")) - .isEqualTo("foo_"); + assertThat(ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix")).isEqualTo("foo_"); } @Configuration @@ -117,8 +111,7 @@ public class TaskExecutionDaoFactoryBeanTests { @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2); return builder.build(); } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TaskExecutionCreator.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TaskExecutionCreator.java index 71a9db60..e6721889 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TaskExecutionCreator.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TaskExecutionCreator.java @@ -38,8 +38,7 @@ public final class TaskExecutionCreator { * @param taskRepository the taskRepository where the taskExecution should be stored. * @return the taskExecution created. */ - public static TaskExecution createAndStoreEmptyTaskExecution( - TaskRepository taskRepository) { + public static TaskExecution createAndStoreEmptyTaskExecution(TaskRepository taskRepository) { return taskRepository.createTaskExecution(); } @@ -48,8 +47,7 @@ public final class TaskExecutionCreator { * @param taskRepository the taskRepository where the taskExecution should be stored. * @return the taskExecution created. */ - public static TaskExecution createAndStoreTaskExecutionNoParams( - TaskRepository taskRepository) { + public static TaskExecution createAndStoreTaskExecutionNoParams(TaskRepository taskRepository) { TaskExecution expectedTaskExecution = taskRepository.createTaskExecution(); return expectedTaskExecution; } @@ -59,10 +57,8 @@ public final class TaskExecutionCreator { * @param taskRepository the taskRepository where the taskExecution should be stored. * @return the taskExecution created. */ - public static TaskExecution createAndStoreTaskExecutionWithParams( - TaskRepository taskRepository) { - TaskExecution expectedTaskExecution = TestVerifierUtils - .createSampleTaskExecutionNoArg(); + public static TaskExecution createAndStoreTaskExecutionWithParams(TaskRepository taskRepository) { + TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); List params = new ArrayList<>(); params.add(UUID.randomUUID().toString()); params.add(UUID.randomUUID().toString()); @@ -77,13 +73,10 @@ public final class TaskExecutionCreator { * @param expectedTaskExecution the expected task execution. * @return the taskExecution created. */ - public static TaskExecution completeExecution(TaskRepository taskRepository, - TaskExecution expectedTaskExecution) { - return taskRepository.completeTaskExecution( - expectedTaskExecution.getExecutionId(), + public static TaskExecution completeExecution(TaskRepository taskRepository, TaskExecution expectedTaskExecution) { + return taskRepository.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), - expectedTaskExecution.getExitMessage(), - expectedTaskExecution.getErrorMessage()); + expectedTaskExecution.getExitMessage(), expectedTaskExecution.getErrorMessage()); } } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDBUtils.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDBUtils.java index 4f28cfce..a1737049 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDBUtils.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDBUtils.java @@ -63,29 +63,22 @@ public final class TestDBUtils { * @param taskExecutionId The id of the task to search. * @return taskExecution retrieved from the database. */ - public static TaskExecution getTaskExecutionFromDB(DataSource dataSource, - long taskExecutionId) { - String sql = "SELECT * FROM TASK_EXECUTION WHERE " + "TASK_EXECUTION_ID = '" - + taskExecutionId + "'"; + public static TaskExecution getTaskExecutionFromDB(DataSource dataSource, long taskExecutionId) { + String sql = "SELECT * FROM TASK_EXECUTION WHERE " + "TASK_EXECUTION_ID = '" + taskExecutionId + "'"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - List rows = jdbcTemplate.query(sql, - new RowMapper() { - @Override - public TaskExecution mapRow(ResultSet rs, int rownumber) - throws SQLException { - TaskExecution taskExecution = new TaskExecution( - rs.getLong("TASK_EXECUTION_ID"), - StringUtils.hasText(rs.getString("EXIT_CODE")) - ? Integer.valueOf(rs.getString("EXIT_CODE")) - : null, - rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"), - rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"), - new ArrayList<>(0), rs.getString("ERROR_MESSAGE"), - rs.getString("EXTERNAL_EXECUTION_ID")); - return taskExecution; - } - }); + List rows = jdbcTemplate.query(sql, new RowMapper() { + @Override + public TaskExecution mapRow(ResultSet rs, int rownumber) throws SQLException { + TaskExecution taskExecution = new TaskExecution(rs.getLong("TASK_EXECUTION_ID"), + StringUtils.hasText(rs.getString("EXIT_CODE")) ? Integer.valueOf(rs.getString("EXIT_CODE")) + : null, + rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"), rs.getTimestamp("END_TIME"), + rs.getString("EXIT_MESSAGE"), new ArrayList<>(0), rs.getString("ERROR_MESSAGE"), + rs.getString("EXTERNAL_EXECUTION_ID")); + return taskExecution; + } + }); assertThat(rows.size()).as("only one row should be returned").isEqualTo(1); TaskExecution taskExecution = rows.get(0); @@ -101,8 +94,7 @@ public final class TestDBUtils { * @throws Exception exception thrown if error occurs creating * {@link PagingQueryProvider}. */ - public static PagingQueryProvider getPagingQueryProvider(String databaseProductName) - throws Exception { + public static PagingQueryProvider getPagingQueryProvider(String databaseProductName) throws Exception { return getPagingQueryProvider(databaseProductName, null); } @@ -115,8 +107,8 @@ public final class TestDBUtils { * @throws Exception exception thrown if error occurs creating * {@link PagingQueryProvider}. */ - public static PagingQueryProvider getPagingQueryProvider(String databaseProductName, - String whereClause) throws Exception { + public static PagingQueryProvider getPagingQueryProvider(String databaseProductName, String whereClause) + throws Exception { DataSource dataSource = getMockDataSource(databaseProductName); Map orderMap = new TreeMap<>(); orderMap.put("START_TIME", Order.DESCENDING); @@ -147,8 +139,7 @@ public final class TestDBUtils { * @throws Exception exception thrown if error occurs creating mock * {@link DataSource}. */ - public static DataSource getMockDataSource(String databaseProductName) - throws Exception { + public static DataSource getMockDataSource(String databaseProductName) throws Exception { DatabaseMetaData dmd = mock(DatabaseMetaData.class); DataSource ds = mock(DataSource.class); Connection con = mock(Connection.class); @@ -180,10 +171,9 @@ public final class TestDBUtils { return incrementerFactory.getIncrementer(databaseType, "TASK_SEQ"); } - private static void populateParamsToDB(DataSource dataSource, - TaskExecution taskExecution) { - String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '" - + taskExecution.getExecutionId() + "'"; + private static void populateParamsToDB(DataSource dataSource, TaskExecution taskExecution) { + String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '" + taskExecution.getExecutionId() + + "'"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List> rows = jdbcTemplate.queryForList(sql); diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDefaultConfiguration.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDefaultConfiguration.java index 0c5e5ee8..1d625fc9 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDefaultConfiguration.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestDefaultConfiguration.java @@ -86,11 +86,12 @@ public class TestDefaultConfiguration implements InitializingBean { @Bean public TaskLifecycleListener taskHandler(TaskExplorer taskExplorer, - @Autowired(required = false) io.micrometer.core.instrument.MeterRegistry meterRegistry, @Autowired(required = false) ObservationRegistry observationRegistry) { + @Autowired(required = false) io.micrometer.core.instrument.MeterRegistry meterRegistry, + @Autowired(required = false) ObservationRegistry observationRegistry) { - return new TaskLifecycleListener(taskRepository(), taskNameResolver(), - this.applicationArguments, taskExplorer, this.taskProperties, - taskListenerExecutorObjectProvider(this.context), observationRegistry, new TaskObservationCloudKeyValues()); + return new TaskLifecycleListener(taskRepository(), taskNameResolver(), this.applicationArguments, taskExplorer, + this.taskProperties, taskListenerExecutorObjectProvider(this.context), observationRegistry, + new TaskObservationCloudKeyValues()); } @Override diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestVerifierUtils.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestVerifierUtils.java index 5c13a636..872c15d7 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestVerifierUtils.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestVerifierUtils.java @@ -71,13 +71,11 @@ public final class TestVerifierUtils { * @param mockAppender The appender that is associated with the test. * @param logSample The string to search for in the log entry. */ - public static void verifyLogEntryExists(Appender mockAppender, - final String logSample) { + public static void verifyLogEntryExists(Appender mockAppender, final String logSample) { verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { - return ((LoggingEvent) argument).getFormattedMessage() - .contains(logSample); + return ((LoggingEvent) argument).getFormattedMessage().contains(logSample); } })); } @@ -92,8 +90,7 @@ public final class TestVerifierUtils { long executionId = randomGenerator.nextLong(); String taskName = UUID.randomUUID().toString(); - return new TaskExecution(executionId, null, taskName, startTime, null, null, - new ArrayList<>(), null, null); + return new TaskExecution(executionId, null, taskName, startTime, null, null, new ArrayList<>(), null, null); } /** @@ -109,8 +106,8 @@ public final class TestVerifierUtils { String taskName = UUID.randomUUID().toString(); String exitMessage = UUID.randomUUID().toString(); - return new TaskExecution(executionId, exitCode, taskName, startTime, endTime, - exitMessage, new ArrayList<>(), null, null); + return new TaskExecution(executionId, exitCode, taskName, startTime, endTime, exitMessage, new ArrayList<>(), + null, null); } /** @@ -126,8 +123,7 @@ public final class TestVerifierUtils { for (int i = 0; i < ARG_SIZE; i++) { args.add(UUID.randomUUID().toString()); } - return new TaskExecution(executionId, null, taskName, startTime, null, null, args, - null, externalExecutionId); + return new TaskExecution(executionId, null, taskName, startTime, null, null, args, null, externalExecutionId); } /** @@ -135,10 +131,8 @@ public final class TestVerifierUtils { * @param expectedTaskExecution The expected value for the task execution. * @param actualTaskExecution The actual value for the task execution. */ - public static void verifyTaskExecution(TaskExecution expectedTaskExecution, - TaskExecution actualTaskExecution) { - assertThat(actualTaskExecution.getExecutionId()) - .as("taskExecutionId must be equal") + public static void verifyTaskExecution(TaskExecution expectedTaskExecution, TaskExecution actualTaskExecution) { + assertThat(actualTaskExecution.getExecutionId()).as("taskExecutionId must be equal") .isEqualTo(expectedTaskExecution.getExecutionId()); if (actualTaskExecution.getStartTime() != null) { assertThat(actualTaskExecution.getStartTime()).as("startTime must be equal") @@ -156,31 +150,26 @@ public final class TestVerifierUtils { .isEqualTo(expectedTaskExecution.getExitMessage()); assertThat(actualTaskExecution.getErrorMessage()).as("errorMessage must be equal") .isEqualTo(expectedTaskExecution.getErrorMessage()); - assertThat(actualTaskExecution.getExternalExecutionId()) - .as("externalExecutionId must be equal") + assertThat(actualTaskExecution.getExternalExecutionId()).as("externalExecutionId must be equal") .isEqualTo(expectedTaskExecution.getExternalExecutionId()); - assertThat(actualTaskExecution.getParentExecutionId()) - .as("parentExecutionId must be equal") + assertThat(actualTaskExecution.getParentExecutionId()).as("parentExecutionId must be equal") .isEqualTo(expectedTaskExecution.getParentExecutionId()); if (expectedTaskExecution.getArguments() != null) { - assertThat(actualTaskExecution.getArguments()) - .as("arguments should not be null").isNotNull(); + assertThat(actualTaskExecution.getArguments()).as("arguments should not be null").isNotNull(); assertThat(actualTaskExecution.getArguments().size()) .as("arguments result set count should match expected count") .isEqualTo(expectedTaskExecution.getArguments().size()); } else { - assertThat(actualTaskExecution.getArguments()).as("arguments should be null") - .isNull(); + assertThat(actualTaskExecution.getArguments()).as("arguments should be null").isNull(); } Set args = new HashSet<>(); for (String param : expectedTaskExecution.getArguments()) { args.add(param); } for (String arg : actualTaskExecution.getArguments()) { - assertThat(args.contains(arg)).as("arg must exist in the repository") - .isTrue(); + assertThat(args.contains(arg)).as("arg must exist in the repository").isTrue(); } } diff --git a/spring-cloud-task-integration-tests/src/test/java/configuration/JobConfiguration.java b/spring-cloud-task-integration-tests/src/test/java/configuration/JobConfiguration.java index 12b0a8c0..2afcbdeb 100644 --- a/spring-cloud-task-integration-tests/src/test/java/configuration/JobConfiguration.java +++ b/spring-cloud-task-integration-tests/src/test/java/configuration/JobConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration @EnableBatchProcessing -@ConditionalOnProperty(prefix = "spring.cloud.task.test", name = "enable-job-configuration", - havingValue = "true") +@ConditionalOnProperty(prefix = "spring.cloud.task.test", name = "enable-job-configuration", havingValue = "true") public class JobConfiguration { private static final int DEFAULT_CHUNK_COUNT = 3; @@ -62,8 +61,7 @@ public class JobConfiguration { public Step step1() { return this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { System.out.println("Executed"); return RepeatStatus.FINISHED; } @@ -72,8 +70,7 @@ public class JobConfiguration { @Bean public Step step2() { - return this.stepBuilderFactory.get("step2") - .chunk(DEFAULT_CHUNK_COUNT) + return this.stepBuilderFactory.get("step2").chunk(DEFAULT_CHUNK_COUNT) .reader(new ListItemReader<>(Arrays.asList("1", "2", "3", "4", "5", "6"))) .processor(new ItemProcessor() { @Override diff --git a/spring-cloud-task-integration-tests/src/test/java/configuration/JobSkipConfiguration.java b/spring-cloud-task-integration-tests/src/test/java/configuration/JobSkipConfiguration.java index 3bdb073e..55dac5e0 100644 --- a/spring-cloud-task-integration-tests/src/test/java/configuration/JobSkipConfiguration.java +++ b/spring-cloud-task-integration-tests/src/test/java/configuration/JobSkipConfiguration.java @@ -54,8 +54,7 @@ public class JobSkipConfiguration { public Step step1() { return this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { System.out.println("Executed"); return RepeatStatus.FINISHED; } @@ -64,10 +63,8 @@ public class JobSkipConfiguration { @Bean public Step step2() { - return this.stepBuilderFactory.get("step2").chunk(3).faultTolerant() - .skip(IllegalStateException.class).skipLimit(100) - .reader(new SkipItemReader()) - .processor(new ItemProcessor() { + return this.stepBuilderFactory.get("step2").chunk(3).faultTolerant().skip(IllegalStateException.class) + .skipLimit(100).reader(new SkipItemReader()).processor(new ItemProcessor() { @Override public String process(Object item) throws Exception { return String.valueOf(Integer.parseInt((String) item) * -1); diff --git a/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemReader.java b/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemReader.java index a6fdbd5e..ae50e50e 100644 --- a/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemReader.java +++ b/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemReader.java @@ -31,8 +31,7 @@ public class SkipItemReader implements ItemReader { boolean finished = false; @Override - public Object read() throws Exception, UnexpectedInputException, ParseException, - NonTransientResourceException { + public Object read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { String result = "1"; if (this.failCount < 2) { this.failCount++; diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartTests.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartTests.java index be13facf..27796a7e 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartTests.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartTests.java @@ -72,8 +72,7 @@ public class TaskStartTests { private final static int MAX_WAIT_TIME = 5000; - private final static String URL = "maven://io.spring.cloud:" - + "timestamp-task:jar:1.1.0.RELEASE"; + private final static String URL = "maven://io.spring.cloud:" + "timestamp-task:jar:1.1.0.RELEASE"; private final static String DATASOURCE_URL; @@ -89,8 +88,8 @@ public class TaskStartTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } private DataSource dataSource; @@ -113,8 +112,7 @@ public class TaskStartTests { @Autowired public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; - TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean( - dataSource); + TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource); this.taskExplorer = new SimpleTaskExplorer(factoryBean); this.taskRepository = new SimpleTaskRepository(factoryBean); } @@ -125,8 +123,7 @@ public class TaskStartTests { this.properties.put("spring.datasource.url", DATASOURCE_URL); this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME); this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD); - this.properties.put("spring.datasource.driverClassName", - DATASOURCE_DRIVER_CLASS_NAME); + this.properties.put("spring.datasource.driverClassName", DATASOURCE_DRIVER_CLASS_NAME); this.properties.put("spring.application.name", TASK_NAME); this.properties.put("spring.cloud.task.initialize-enabled", "false"); @@ -151,8 +148,7 @@ public class TaskStartTests { initializer.setDataSource(this.dataSource); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.addScript( - new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql")); + databasePopulator.addScript(new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql")); initializer.setDatabasePopulator(databasePopulator); initializer.afterPropertiesSet(); } @@ -160,41 +156,33 @@ public class TaskStartTests { @Test public void testWithGeneratedTaskExecution() throws Exception { this.taskRepository.createTaskExecution(); - assertThat(this.taskExplorer.getTaskExecutionCount()) - .as("Only one row is expected").isEqualTo(1); + assertThat(this.taskExplorer.getTaskExecutionCount()).as("Only one row is expected").isEqualTo(1); this.applicationContext = getTaskApplication(1).run(new String[0]); assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertThat(taskExecutions.getTotalElements()).as("Only one row is expected") - .isEqualTo(1); - assertThat(taskExecutions.iterator().next().getExitCode().intValue()) - .as("return code should be 0").isEqualTo(0); + assertThat(taskExecutions.getTotalElements()).as("Only one row is expected").isEqualTo(1); + assertThat(taskExecutions.iterator().next().getExitCode().intValue()).as("return code should be 0") + .isEqualTo(0); } @Test public void testWithGeneratedTaskExecutionWithName() throws Exception { final String TASK_EXECUTION_NAME = "PRE-EXECUTION-TEST-NAME"; this.taskRepository.createTaskExecution(TASK_EXECUTION_NAME); - assertThat(this.taskExplorer.getTaskExecutionCount()) - .as("Only one row is expected").isEqualTo(1); - assertThat(this.taskExplorer.getTaskExecution(1).getTaskName()) - .isEqualTo(TASK_EXECUTION_NAME); + assertThat(this.taskExplorer.getTaskExecutionCount()).as("Only one row is expected").isEqualTo(1); + assertThat(this.taskExplorer.getTaskExecution(1).getTaskName()).isEqualTo(TASK_EXECUTION_NAME); this.applicationContext = getTaskApplication(1).run(new String[0]); assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertThat(taskExecutions.getTotalElements()).as("Only one row is expected") - .isEqualTo(1); - assertThat(taskExecutions.iterator().next().getExitCode().intValue()) - .as("return code should be 0").isEqualTo(0); - assertThat(this.taskExplorer.getTaskExecution(1).getTaskName()) - .isEqualTo("batchEvents"); + assertThat(taskExecutions.getTotalElements()).as("Only one row is expected").isEqualTo(1); + assertThat(taskExecutions.iterator().next().getExitCode().intValue()).as("return code should be 0") + .isEqualTo(0); + assertThat(this.taskExplorer.getTaskExecution(1).getTaskName()).isEqualTo("batchEvents"); } @Test @@ -207,8 +195,7 @@ public class TaskStartTests { @Test public void testCompletedTaskExecution() throws Exception { this.taskRepository.createTaskExecution(); - assertThat(this.taskExplorer.getTaskExecutionCount()) - .as("Only one row is expected").isEqualTo(1); + assertThat(this.taskExplorer.getTaskExecutionCount()).as("Only one row is expected").isEqualTo(1); this.taskRepository.completeTaskExecution(1, 0, new Date(), ""); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> { this.applicationContext = getTaskApplication(1).run(new String[0]); @@ -217,26 +204,21 @@ public class TaskStartTests { @Test public void testDuplicateTaskExecutionWithSingleInstanceEnabled() throws Exception { - String[] params = { "--spring.cloud.task.single-instance-enabled=true", - "--spring.cloud.task.name=foo" }; + String[] params = { "--spring.cloud.task.single-instance-enabled=true", "--spring.cloud.task.name=foo" }; boolean testFailed = false; try { this.taskRepository.createTaskExecution(); - assertThat(this.taskExplorer.getTaskExecutionCount()) - .as("Only one row is expected").isEqualTo(1); + assertThat(this.taskExplorer.getTaskExecutionCount()).as("Only one row is expected").isEqualTo(1); enableLock("foo"); getTaskApplication(1).run(params); } catch (ApplicationContextException taskException) { - assertThat(taskException.getMessage()) - .isEqualTo("Failed to start bean 'taskLifecycleListener'; nested " - + "exception is org.springframework.cloud.task." - + "listener.TaskExecutionException: Failed to process " - + "@BeforeTask or @AfterTask annotation because: Task with name \"foo\" is already running."); + assertThat(taskException.getCause().getMessage()).isEqualTo("Failed to process " + + "@BeforeTask or @AfterTask annotation because: Task with name \"foo\" is already running."); testFailed = true; } - assertThat(testFailed).as("Expected TaskExecutionException for because of " - + "single-instance-enabled is enabled").isTrue(); + assertThat(testFailed) + .as("Expected TaskExecutionException for because of " + "single-instance-enabled is enabled").isTrue(); } @@ -244,8 +226,7 @@ public class TaskStartTests { public void testDuplicateTaskExecutionWithSingleInstanceDisabled() throws Exception { this.taskRepository.createTaskExecution(); TaskExecution execution = this.taskRepository.createTaskExecution(); - this.taskRepository.startTaskExecution(execution.getExecutionId(), "bar", - new Date(), new ArrayList<>(), ""); + this.taskRepository.startTaskExecution(execution.getExecutionId(), "bar", new Date(), new ArrayList<>(), ""); String[] params = { "--spring.cloud.task.name=bar" }; enableLock("bar"); this.applicationContext = getTaskApplication(1).run(params); @@ -258,8 +239,7 @@ public class TaskStartTests { ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); myMap.put("spring.cloud.task.executionid", executionId); - propertySources - .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); myapp.setEnvironment(environment); return myapp; } @@ -267,8 +247,7 @@ public class TaskStartTests { private boolean tableExists() throws SQLException { boolean result; try (Connection conn = this.dataSource.getConnection(); - ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", - new String[] { "TABLE" })) { + ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", new String[] { "TABLE" })) { result = res.next(); } return result; @@ -287,11 +266,9 @@ public class TaskStartTests { } private void enableLock(String lockKey) { - SimpleJdbcInsert taskLockInsert = new SimpleJdbcInsert(this.dataSource) - .withTableName("TASK_LOCK"); + SimpleJdbcInsert taskLockInsert = new SimpleJdbcInsert(this.dataSource).withTableName("TASK_LOCK"); Map taskLockParams = new HashMap<>(); - taskLockParams.put("LOCK_KEY", - UUID.nameUUIDFromBytes(lockKey.getBytes()).toString()); + taskLockParams.put("LOCK_KEY", UUID.nameUUIDFromBytes(lockKey.getBytes()).toString()); taskLockParams.put("REGION", "DEFAULT"); taskLockParams.put("CLIENT_ID", "aClientID"); taskLockParams.put("CREATED_DATE", new Date()); @@ -308,9 +285,8 @@ public class TaskStartTests { Server server = null; try { if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); defaultServer = server; } } diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/initializer/TaskInitializerTests.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/initializer/TaskInitializerTests.java index d3aaf4ba..de1b4d44 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/initializer/TaskInitializerTests.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/initializer/TaskInitializerTests.java @@ -47,7 +47,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.context.junit.jupiter.SpringExtension; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -59,8 +58,7 @@ public class TaskInitializerTests { private final static int MAX_WAIT_TIME = 5000; - private final static String URL = "maven://io.spring.cloud:" - + "timestamp-task:jar:1.1.0.RELEASE"; + private final static String URL = "maven://io.spring.cloud:" + "timestamp-task:jar:1.1.0.RELEASE"; private final static String DATASOURCE_URL; @@ -76,8 +74,8 @@ public class TaskInitializerTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } private DataSource dataSource; @@ -96,8 +94,7 @@ public class TaskInitializerTests { @Autowired public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; - TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean( - dataSource); + TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource); this.taskExplorer = new SimpleTaskExplorer(factoryBean); } @@ -138,13 +135,11 @@ public class TaskInitializerTests { this.applicationContext = myapp.run(properties); assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertThat(taskExecutions.getTotalElements()).as("Only one row is expected") - .isEqualTo(1); - assertThat(taskExecutions.iterator().next().getExitCode().intValue()) - .as("return code should be 0").isEqualTo(0); + assertThat(taskExecutions.getTotalElements()).as("Only one row is expected").isEqualTo(1); + assertThat(taskExecutions.iterator().next().getExitCode().intValue()).as("return code should be 0") + .isEqualTo(0); } @Test @@ -163,20 +158,17 @@ public class TaskInitializerTests { this.applicationContext = myapp.run(properties); assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertThat(taskExecutions.getTotalElements()).as("Only one row is expected") - .isEqualTo(1); - assertThat(taskExecutions.iterator().next().getExitCode().intValue()) - .as("return code should be 0").isEqualTo(0); + assertThat(taskExecutions.getTotalElements()).as("Only one row is expected").isEqualTo(1); + assertThat(taskExecutions.iterator().next().getExitCode().intValue()).as("return code should be 0") + .isEqualTo(0); } private boolean tableExists() throws SQLException { boolean result; try (Connection conn = this.dataSource.getConnection(); - ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", - new String[] { "TABLE" })) { + ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", new String[] { "TABLE" })) { result = res.next(); } return result; @@ -204,9 +196,8 @@ public class TaskInitializerTests { Server server = null; try { if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); defaultServer = server; } } diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java index 5b127fd4..00fdb51f 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java @@ -56,21 +56,17 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) -@SpringBootTest( - classes = { TaskLauncherSinkApplication.class, - TaskLauncherSinkTests.TaskLauncherConfiguration.class }, - properties = { - "maven.remote-repositories.repo1.url=https://repo.spring.io/libs-release", - "spring.cloud.stream.function.bindings.taskLauncherSink-in-0=input", - "spring.cloud.stream.bindings.input.destination=taskLauncherSinkExchange" }) +@SpringBootTest(classes = { TaskLauncherSinkApplication.class, TaskLauncherSinkTests.TaskLauncherConfiguration.class }, + properties = { "maven.remote-repositories.repo1.url=https://repo.spring.io/libs-release", + "spring.cloud.stream.function.bindings.taskLauncherSink-in-0=input", + "spring.cloud.stream.bindings.input.destination=taskLauncherSinkExchange" }) public class TaskLauncherSinkTests { private final static int WAIT_INTERVAL = 500; private final static int MAX_WAIT_TIME = 120000; - private final static String URL = "maven://io.spring.cloud:" - + "timestamp-task:3.0.0-SNAPSHOT"; + private final static String URL = "maven://io.spring.cloud:" + "timestamp-task:3.0.0-SNAPSHOT"; private final static String DATASOURCE_URL; @@ -86,8 +82,8 @@ public class TaskLauncherSinkTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } @Autowired @@ -102,8 +98,7 @@ public class TaskLauncherSinkTests { @Autowired public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; - this.taskExplorer = new SimpleTaskExplorer( - new TaskExecutionDaoFactoryBean(dataSource)); + this.taskExplorer = new SimpleTaskExplorer(new TaskExecutionDaoFactoryBean(dataSource)); } @BeforeEach @@ -112,8 +107,7 @@ public class TaskLauncherSinkTests { this.properties.put("spring.datasource.url", DATASOURCE_URL); this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME); this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD); - this.properties.put("spring.datasource.driverClassName", - DATASOURCE_DRIVER_CLASS_NAME); + this.properties.put("spring.datasource.driverClassName", DATASOURCE_DRIVER_CLASS_NAME); this.properties.put("spring.application.name", TASK_NAME); JdbcTemplate template = new JdbcTemplate(this.dataSource); @@ -123,8 +117,7 @@ public class TaskLauncherSinkTests { initializer.setDataSource(this.dataSource); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - databasePopulator.addScript( - new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql")); + databasePopulator.addScript(new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql")); initializer.setDatabasePopulator(databasePopulator); initializer.afterPropertiesSet(); @@ -135,20 +128,17 @@ public class TaskLauncherSinkTests { launchTask(URL); assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); - assertThat(taskExecutions.getTotalElements()).as("Only one row is expected") - .isEqualTo(1); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); + assertThat(taskExecutions.getTotalElements()).as("Only one row is expected").isEqualTo(1); assertThat(waitForTaskToComplete()).isTrue(); - assertThat(taskExecutions.iterator().next().getExitCode().intValue()) - .as("return code should be 0").isEqualTo(0); + assertThat(taskExecutions.iterator().next().getExitCode().intValue()).as("return code should be 0") + .isEqualTo(0); } private boolean tableExists() throws SQLException { boolean result; try (Connection conn = this.dataSource.getConnection(); - ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", - new String[] { "TABLE" })) { + ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", new String[] { "TABLE" })) { result = res.next(); } return result; @@ -180,8 +170,7 @@ public class TaskLauncherSinkTests { } private void launchTask(String artifactURL) { - TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, null, - this.properties, null, null); + TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, null, this.properties, null, null); GenericMessage message = new GenericMessage<>(request); this.streamBridge.send("taskLauncherSinkExchange", message); } @@ -201,8 +190,8 @@ public class TaskLauncherSinkTests { public Server initH2TCPServer() { Server server; try { - server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", - "-tcpPort", String.valueOf(randomPort)).start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); } catch (SQLException e) { throw new IllegalStateException(e); diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/BatchExecutionEventTests.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/BatchExecutionEventTests.java index 4b5bd910..c53ca142 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/BatchExecutionEventTests.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/BatchExecutionEventTests.java @@ -29,7 +29,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -51,6 +50,7 @@ public class BatchExecutionEventTests { private static final String TASK_NAME = "taskEventTest"; private final ObjectMapper objectMapper = new ObjectMapper(); + private ConfigurableApplicationContext applicationContext; @BeforeEach @@ -68,45 +68,39 @@ public class BatchExecutionEventTests { @Test public void testContext() { this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(BatchEventsApplication.class)).web(WebApplicationType.NONE) - .build().run(getCommandLineParams( - "--spring.cloud.stream.bindings.job-execution-events.destination=bazbar")); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(BatchEventsApplication.class)) + .web(WebApplicationType.NONE).build() + .run(getCommandLineParams("--spring.cloud.stream.bindings.job-execution-events.destination=bazbar")); - assertThat(this.applicationContext.getBean("jobExecutionEventsListener")) - .isNotNull(); - assertThat(this.applicationContext.getBean("stepExecutionEventsListener")) - .isNotNull(); + assertThat(this.applicationContext.getBean("jobExecutionEventsListener")).isNotNull(); + assertThat(this.applicationContext.getBean("stepExecutionEventsListener")).isNotNull(); assertThat(this.applicationContext.getBean("chunkEventsListener")).isNotNull(); assertThat(this.applicationContext.getBean("itemReadEventsListener")).isNotNull(); - assertThat(this.applicationContext.getBean("itemWriteEventsListener")) - .isNotNull(); - assertThat(this.applicationContext.getBean("itemProcessEventsListener")) - .isNotNull(); + assertThat(this.applicationContext.getBean("itemWriteEventsListener")).isNotNull(); + assertThat(this.applicationContext.getBean("itemProcessEventsListener")).isNotNull(); assertThat(this.applicationContext.getBean("skipEventsListener")).isNotNull(); } @Test public void testJobEventListener() throws Exception { List> result = testListener( - "--spring.cloud.task.batch.events.jobExecutionEventBindingName=foobar", "foobar", 1); + "--spring.cloud.task.batch.events.jobExecutionEventBindingName=foobar", "foobar", 1); JobExecutionEvent jobExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), - JobExecutionEvent.class); - Assertions.assertThat(jobExecutionEvent.getJobInstance().getJobName()) - .isEqualTo("job").as("Job name should be job"); + JobExecutionEvent.class); + Assertions.assertThat(jobExecutionEvent.getJobInstance().getJobName()).isEqualTo("job") + .as("Job name should be job"); } @Test public void testStepEventListener() throws Exception { final String bindingName = "step-execution-foobar"; List> result = testListener( - "--spring.cloud.task.batch.events.stepExecutionEventBindingName=" + bindingName, - bindingName, 4); + "--spring.cloud.task.batch.events.stepExecutionEventBindingName=" + bindingName, bindingName, 4); int stepOneCount = 0; int stepTwoCount = 0; for (int i = 0; i < 4; i++) { StepExecutionEvent stepExecutionEvent = this.objectMapper.readValue(result.get(i).getPayload(), - StepExecutionEvent.class); + StepExecutionEvent.class); if (stepExecutionEvent.getStepName().equals("step1")) { stepOneCount++; } @@ -115,10 +109,8 @@ public class BatchExecutionEventTests { } } - assertThat(stepOneCount).as("the number of step1 events did not match") - .isEqualTo(2); - assertThat(stepTwoCount).as("the number of step2 events did not match") - .isEqualTo(2); + assertThat(stepOneCount).as("the number of step1 events did not match").isEqualTo(2); + assertThat(stepTwoCount).as("the number of step2 events did not match").isEqualTo(2); } @@ -127,8 +119,7 @@ public class BatchExecutionEventTests { final String bindingName = "item-execution-foobar"; List> result = testListener( - "--spring.cloud.task.batch.events.itemProcessEventBindingName=" + bindingName, - bindingName, 1); + "--spring.cloud.task.batch.events.itemProcessEventBindingName=" + bindingName, bindingName, 1); String value = new String(result.get(0).getPayload()); assertThat(value).isEqualTo("item did not equal result after processing"); @@ -139,8 +130,7 @@ public class BatchExecutionEventTests { final String bindingName = "chunk-events-foobar"; List> result = testListener( - "--spring.cloud.task.batch.events.chunkEventBindingName=" + bindingName, - bindingName, 2); + "--spring.cloud.task.batch.events.chunkEventBindingName=" + bindingName, bindingName, 2); String value = new String(result.get(0).getPayload()); assertThat(value).isEqualTo("Before Chunk Processing"); value = new String(result.get(1).getPayload()); @@ -152,8 +142,7 @@ public class BatchExecutionEventTests { final String bindingName = "item-write-events-foobar"; List> result = testListener( - "--spring.cloud.task.batch.events.itemWriteEventBindingName=" + bindingName, - bindingName, 2); + "--spring.cloud.task.batch.events.itemWriteEventBindingName=" + bindingName, bindingName, 2); String value = new String(result.get(0).getPayload()); assertThat(value).isEqualTo("3 items to be written."); value = new String(result.get(1).getPayload()); @@ -165,16 +154,12 @@ public class BatchExecutionEventTests { } private String[] getCommandLineParams(String sinkChannelParam, boolean enableFailJobConfig) { - String jobConfig = enableFailJobConfig ? - "--spring.cloud.task.test.enable-job-configuration=true" : - "--spring.cloud.task.test.enable-fail-job-configuration=true"; - return new String[]{"--spring.cloud.task.closecontext_enable=false", - "--spring.cloud.task.name=" + TASK_NAME, - "--spring.main.web-environment=false", - "--spring.cloud.stream.defaultBinder=rabbit", - "--spring.cloud.stream.bindings.task-events.destination=test", - jobConfig, - "foo=" + UUID.randomUUID(), sinkChannelParam}; + String jobConfig = enableFailJobConfig ? "--spring.cloud.task.test.enable-job-configuration=true" + : "--spring.cloud.task.test.enable-fail-job-configuration=true"; + return new String[] { "--spring.cloud.task.closecontext_enable=false", "--spring.cloud.task.name=" + TASK_NAME, + "--spring.main.web-environment=false", "--spring.cloud.stream.defaultBinder=rabbit", + "--spring.cloud.stream.bindings.task-events.destination=test", jobConfig, "foo=" + UUID.randomUUID(), + sinkChannelParam }; } private List> testListener(String channelBinding, String bindingName, int numberToRead) { @@ -185,14 +170,13 @@ public class BatchExecutionEventTests { return testListenerForApp(channelBinding, bindingName, numberToRead, BatchSkipEventsApplication.class, false); } - private List> testListenerForApp(String channelBinding, - String bindingName, int numberToRead, Class clazz, boolean enableFailJobConfig) { + private List> testListenerForApp(String channelBinding, String bindingName, int numberToRead, + Class clazz, boolean enableFailJobConfig) { List> results = new ArrayList<>(); this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(clazz)).web(WebApplicationType.NONE) - .build().run(getCommandLineParams(channelBinding, enableFailJobConfig)); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(clazz)).web(WebApplicationType.NONE) + .build().run(getCommandLineParams(channelBinding, enableFailJobConfig)); OutputDestination target = this.applicationContext.getBean(OutputDestination.class); @@ -207,8 +191,7 @@ public class BatchExecutionEventTests { final String bindingName = "item-read-events-foobar"; List> result = testListenerSkip( - "--spring.cloud.task.batch.events.itemReadEventBindingName=" + bindingName, - bindingName, 1); + "--spring.cloud.task.batch.events.itemReadEventBindingName=" + bindingName, bindingName, 1); String exceptionMessage = new String(result.get(0).getPayload()); assertThat(exceptionMessage).isEqualTo("Exception while item was being read"); } @@ -220,8 +203,7 @@ public class BatchExecutionEventTests { final String SKIPPING_WRITE_CONTENT = "-1"; final String bindingName = "skip-event-foobar"; List> result = testListenerSkip( - "--spring.cloud.task.batch.events.skipEventBindingName=" + bindingName, - bindingName, 3); + "--spring.cloud.task.batch.events.skipEventBindingName=" + bindingName, bindingName, 3); int readSkipCount = 0; int writeSkipCount = 0; for (int i = 0; i < 3; i++) { @@ -234,19 +216,20 @@ public class BatchExecutionEventTests { } } - assertThat(readSkipCount).as("the number of read skip events did not match") - .isEqualTo(2); - assertThat(writeSkipCount).as("the number of write skip events did not match") - .isEqualTo(1); + assertThat(readSkipCount).as("the number of read skip events did not match").isEqualTo(2); + assertThat(writeSkipCount).as("the number of write skip events did not match").isEqualTo(1); } @SpringBootApplication @Import(JobConfiguration.class) public static class BatchEventsApplication { + } @SpringBootApplication @Import(JobSkipConfiguration.class) public static class BatchSkipEventsApplication { + } + } diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java index 5f8aa348..b58893af 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java @@ -57,24 +57,21 @@ public class TaskEventTests { @Test public void testTaskEventListener() throws Exception { List> result = testListener( - "--spring.cloud.task.batch.events.itemWriteEventBindingName=task-events", - "task-events", 2); - TaskExecution taskExecution = this.objectMapper.readValue(result.get(0).getPayload(), - TaskExecution.class); + "--spring.cloud.task.batch.events.itemWriteEventBindingName=task-events", "task-events", 2); + TaskExecution taskExecution = this.objectMapper.readValue(result.get(0).getPayload(), TaskExecution.class); Assertions.assertThat(taskExecution.getTaskName()).isEqualTo(TASK_NAME) - .as(String.format("Task name should be '%s'", TASK_NAME)); - taskExecution = this.objectMapper.readValue(result.get(1).getPayload(), - TaskExecution.class); + .as(String.format("Task name should be '%s'", TASK_NAME)); + taskExecution = this.objectMapper.readValue(result.get(1).getPayload(), TaskExecution.class); Assertions.assertThat(taskExecution.getTaskName()).isEqualTo(TASK_NAME) - .as(String.format("Task name should be '%s'", TASK_NAME)); + .as(String.format("Task name should be '%s'", TASK_NAME)); } private List> testListener(String channelBinding, String bindingName, int numberToRead) { List> results = new ArrayList<>(); this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(BatchExecutionEventTests.BatchEventsApplication.class)).web(WebApplicationType.NONE).build() - .run(getCommandLineParams(channelBinding)); + .sources(TestChannelBinderConfiguration + .getCompleteConfiguration(BatchExecutionEventTests.BatchEventsApplication.class)) + .web(WebApplicationType.NONE).build().run(getCommandLineParams(channelBinding)); OutputDestination target = this.applicationContext.getBean(OutputDestination.class); for (int i = 0; i < numberToRead; i++) { results.add(target.receive(10000, bindingName)); @@ -83,11 +80,9 @@ public class TaskEventTests { } private String[] getCommandLineParams(String sinkChannelParam) { - return new String[]{"--spring.cloud.task.closecontext_enable=false", - "--spring.cloud.task.name=" + TASK_NAME, - "--spring.main.web-environment=false", - "--spring.cloud.stream.defaultBinder=rabbit", - "foo=" + UUID.randomUUID(), sinkChannelParam}; + return new String[] { "--spring.cloud.task.closecontext_enable=false", "--spring.cloud.task.name=" + TASK_NAME, + "--spring.main.web-environment=false", "--spring.cloud.stream.defaultBinder=rabbit", + "foo=" + UUID.randomUUID(), sinkChannelParam }; } @EnableTask @@ -95,4 +90,5 @@ public class TaskEventTests { public static class TaskEventsConfiguration { } + } diff --git a/spring-cloud-task-samples/batch-events/src/main/java/io/spring/cloud/BatchEventsApplication.java b/spring-cloud-task-samples/batch-events/src/main/java/io/spring/cloud/BatchEventsApplication.java index c40c362f..01aa2fbd 100644 --- a/spring-cloud-task-samples/batch-events/src/main/java/io/spring/cloud/BatchEventsApplication.java +++ b/spring-cloud-task-samples/batch-events/src/main/java/io/spring/cloud/BatchEventsApplication.java @@ -60,43 +60,39 @@ public class BatchEventsApplication { @Bean public Step step1() { - return this.stepBuilderFactory.get("step1") - .tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - System.out.println("Tasklet has run"); - return RepeatStatus.FINISHED; - } - }).build(); + return this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + System.out.println("Tasklet has run"); + return RepeatStatus.FINISHED; + } + }).build(); } @Bean public Step step2() { - return this.stepBuilderFactory.get("step2") - .chunk(DEFAULT_CHUNK_COUNT) - .reader(new ListItemReader<>(Arrays.asList("1", "2", "3", "4", "5", "6"))) - .processor(new ItemProcessor() { - @Override - public String process(String item) throws Exception { - return String.valueOf(Integer.parseInt(item) * -1); - } - }) - .writer(new ItemWriter() { - @Override - public void write(List items) throws Exception { - for (String item : items) { - System.out.println(">> " + item); + return this.stepBuilderFactory.get("step2").chunk(DEFAULT_CHUNK_COUNT) + .reader(new ListItemReader<>(Arrays.asList("1", "2", "3", "4", "5", "6"))) + .processor(new ItemProcessor() { + @Override + public String process(String item) throws Exception { + return String.valueOf(Integer.parseInt(item) * -1); } - } - }).build(); + }).writer(new ItemWriter() { + @Override + public void write(List items) throws Exception { + for (String item : items) { + System.out.println(">> " + item); + } + } + }).build(); } @Bean public Job job() { - return this.jobBuilderFactory.get("job") - .start(step1()) - .next(step2()) - .build(); + return this.jobBuilderFactory.get("job").start(step1()).next(step2()).build(); } + } + } diff --git a/spring-cloud-task-samples/batch-events/src/test/java/io/spring/cloud/BatchEventsApplicationTests.java b/spring-cloud-task-samples/batch-events/src/test/java/io/spring/cloud/BatchEventsApplicationTests.java index bcf73429..9eca1502 100644 --- a/spring-cloud-task-samples/batch-events/src/test/java/io/spring/cloud/BatchEventsApplicationTests.java +++ b/spring-cloud-task-samples/batch-events/src/test/java/io/spring/cloud/BatchEventsApplicationTests.java @@ -42,6 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; @Tag("DockerRequired") public class BatchEventsApplicationTests { + private static final String TASK_NAME = "taskEventTest"; private ConfigurableApplicationContext applicationContext; @@ -64,33 +65,25 @@ public class BatchEventsApplicationTests { @Test public void testExecution() throws Exception { - List> result = testListener( - taskEventProperties.getJobExecutionEventBindingName(), 1); + List> result = testListener(taskEventProperties.getJobExecutionEventBindingName(), 1); JobExecutionEvent jobExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), - JobExecutionEvent.class); - assertThat(jobExecutionEvent.getJobInstance().getJobName()) - .isEqualTo("job").as("Job name should be job"); + JobExecutionEvent.class); + assertThat(jobExecutionEvent.getJobInstance().getJobName()).isEqualTo("job").as("Job name should be job"); } private String[] getCommandLineParams(boolean enableFailJobConfig) { - String jobConfig = enableFailJobConfig ? - "--spring.cloud.task.test.enable-job-configuration=true" : - "--spring.cloud.task.test.enable-fail-job-configuration=true"; - return new String[]{"--spring.cloud.task.closecontext_enable=false", - "--spring.cloud.task.name=" + TASK_NAME, - "--spring.main.web-environment=false", - "--spring.cloud.stream.defaultBinder=rabbit", - "--spring.cloud.stream.bindings.task-events.destination=test", - jobConfig, - "foo=" + UUID.randomUUID()}; + String jobConfig = enableFailJobConfig ? "--spring.cloud.task.test.enable-job-configuration=true" + : "--spring.cloud.task.test.enable-fail-job-configuration=true"; + return new String[] { "--spring.cloud.task.closecontext_enable=false", "--spring.cloud.task.name=" + TASK_NAME, + "--spring.main.web-environment=false", "--spring.cloud.stream.defaultBinder=rabbit", + "--spring.cloud.stream.bindings.task-events.destination=test", jobConfig, "foo=" + UUID.randomUUID() }; } private List> testListener(String bindingName, int numberToRead) { List> results = new ArrayList<>(); this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(BatchEventsTestApplication.class)).web(WebApplicationType.NONE).build() - .run(getCommandLineParams(true)); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(BatchEventsTestApplication.class)) + .web(WebApplicationType.NONE).build().run(getCommandLineParams(true)); OutputDestination target = this.applicationContext.getBean(OutputDestination.class); for (int i = 0; i < numberToRead; i++) { results.add(target.receive(10000, bindingName)); @@ -99,8 +92,9 @@ public class BatchEventsApplicationTests { } @SpringBootApplication - @Import({BatchEventsApplication.class}) + @Import({ BatchEventsApplication.class }) public static class BatchEventsTestApplication { + } } diff --git a/spring-cloud-task-samples/batch-job/src/main/java/io/spring/BatchJobApplication.java b/spring-cloud-task-samples/batch-job/src/main/java/io/spring/BatchJobApplication.java index fb3d8e2e..f0839dce 100644 --- a/spring-cloud-task-samples/batch-job/src/main/java/io/spring/BatchJobApplication.java +++ b/spring-cloud-task-samples/batch-job/src/main/java/io/spring/BatchJobApplication.java @@ -29,4 +29,5 @@ public class BatchJobApplication { public static void main(String[] args) { SpringApplication.run(BatchJobApplication.class, args); } + } diff --git a/spring-cloud-task-samples/batch-job/src/main/java/io/spring/configuration/JobConfiguration.java b/spring-cloud-task-samples/batch-job/src/main/java/io/spring/configuration/JobConfiguration.java index a81c4894..221aadd4 100644 --- a/spring-cloud-task-samples/batch-job/src/main/java/io/spring/configuration/JobConfiguration.java +++ b/spring-cloud-task-samples/batch-job/src/main/java/io/spring/configuration/JobConfiguration.java @@ -46,16 +46,13 @@ public class JobConfiguration { @Bean public Job job1() { - return this.jobBuilderFactory.get("job1") - .start(this.stepBuilderFactory.get("job1step1") - .tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - logger.info("Job1 was run"); - return RepeatStatus.FINISHED; - } - }) - .build()) - .build(); + return this.jobBuilderFactory.get("job1").start(this.stepBuilderFactory.get("job1step1").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + logger.info("Job1 was run"); + return RepeatStatus.FINISHED; + } + }).build()).build(); } + } diff --git a/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java b/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java index 94aa7c61..cc6a0ca2 100644 --- a/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java +++ b/spring-cloud-task-samples/batch-job/src/test/java/io/spring/BatchJobApplicationTests.java @@ -26,7 +26,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -37,7 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(OutputCaptureExtension.class) public class BatchJobApplicationTests { - @Test public void testBatchJobApp(CapturedOutput capturedOutput) throws Exception { final String JOB_RUN_MESSAGE = " was run"; @@ -58,7 +56,6 @@ public class BatchJobApplicationTests { assertThat(i).isGreaterThan(0); - String taskTitle = "Demo Batch Job Task"; Pattern pattern = Pattern.compile(taskTitle); Matcher matcher = pattern.matcher(output); diff --git a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunComponent.java b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunComponent.java index 5a5f5bb2..d06d3fa5 100644 --- a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunComponent.java +++ b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunComponent.java @@ -47,4 +47,5 @@ public class TaskRunComponent { this.taskRunRepository.save(new TaskRunOutput("Executed at " + execDate)); logger.info("Executed at : " + execDate); } + } diff --git a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunOutput.java b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunOutput.java index 143e93dc..7380d047 100644 --- a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunOutput.java +++ b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunOutput.java @@ -31,6 +31,7 @@ import jakarta.persistence.Table; @Entity @Table(name = "TASK_RUN_OUTPUT") public class TaskRunOutput { + @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @@ -64,4 +65,5 @@ public class TaskRunOutput { public String toString() { return "TaskRunOutput{" + "id=" + this.id + ", output='" + this.output + '\'' + '}'; } + } diff --git a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunRepository.java b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunRepository.java index 92d89ac6..e3c841db 100644 --- a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunRepository.java +++ b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/configuration/TaskRunRepository.java @@ -23,4 +23,5 @@ import org.springframework.data.jpa.repository.JpaRepository; * @author Glenn Renfro */ public interface TaskRunRepository extends JpaRepository { + } diff --git a/spring-cloud-task-samples/jpa-sample/src/test/java/io/spring/JpaApplicationTests.java b/spring-cloud-task-samples/jpa-sample/src/test/java/io/spring/JpaApplicationTests.java index a2723faa..f1eafd20 100644 --- a/spring-cloud-task-samples/jpa-sample/src/test/java/io/spring/JpaApplicationTests.java +++ b/spring-cloud-task-samples/jpa-sample/src/test/java/io/spring/JpaApplicationTests.java @@ -27,7 +27,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; - import org.springframework.boot.SpringApplication; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; @@ -59,11 +58,13 @@ public class JpaApplicationTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" - + "DB_CLOSE_ON_EXIT=FALSE"; + + "DB_CLOSE_ON_EXIT=FALSE"; } private ConfigurableApplicationContext context; + private DataSource dataSource; + private Server server; @BeforeEach @@ -76,9 +77,8 @@ public class JpaApplicationTests { this.dataSource = dataSource; try { this.server = Server - .createTcpServer("-tcp", "-ifNotExists", "-tcpAllowOthers", "-tcpPort", String - .valueOf(randomPort)) - .start(); + .createTcpServer("-tcp", "-ifNotExists", "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) + .start(); } catch (SQLException e) { throw new IllegalStateException(e); @@ -96,18 +96,14 @@ public class JpaApplicationTests { @Test public void testBatchJobApp(CapturedOutput capturedOutput) { final String INSERT_MESSAGE = "Hibernate: insert into task_run_output ("; - this.context = SpringApplication - .run(JpaApplication.class, "--spring.datasource.url=" + DATASOURCE_URL, + this.context = SpringApplication.run(JpaApplication.class, "--spring.datasource.url=" + DATASOURCE_URL, "--spring.datasource.username=" + DATASOURCE_USER_NAME, "--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME, "--spring.jpa.database-platform=org.hibernate.dialect.H2Dialect"); String output = capturedOutput.toString(); - assertThat(output - .contains(INSERT_MESSAGE)).as("Unable to find the insert message: " + output) - .isTrue(); + assertThat(output.contains(INSERT_MESSAGE)).as("Unable to find the insert message: " + output).isTrue(); JdbcTemplate template = new JdbcTemplate(this.dataSource); - Map result = template - .queryForMap("Select * from TASK_RUN_OUTPUT"); + Map result = template.queryForMap("Select * from TASK_RUN_OUTPUT"); assertThat(result.get("ID")).isEqualTo(1L); assertThat(((String) result.get("OUTPUT"))).contains("Executed at"); } diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/MultipleDataSourcesApplication.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/MultipleDataSourcesApplication.java index 67851658..1cbcbc7c 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/MultipleDataSourcesApplication.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/MultipleDataSourcesApplication.java @@ -20,7 +20,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.task.configuration.EnableTask; - /** * @author Michael Minella */ diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/CustomTaskConfigurer.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/CustomTaskConfigurer.java index d774518a..820c8183 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/CustomTaskConfigurer.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/CustomTaskConfigurer.java @@ -33,4 +33,5 @@ public class CustomTaskConfigurer extends DefaultTaskConfigurer { public CustomTaskConfigurer(@Qualifier("secondDataSource") DataSource dataSource) { super(dataSource); } + } diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/EmbeddedDataSourceConfiguration.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/EmbeddedDataSourceConfiguration.java index a746168a..5b79d8c3 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/EmbeddedDataSourceConfiguration.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/EmbeddedDataSourceConfiguration.java @@ -36,15 +36,12 @@ public class EmbeddedDataSourceConfiguration { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.HSQL) - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).build(); } @Bean public DataSource secondDataSource() { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2) - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } + } diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/ExternalDataSourceConfiguration.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/ExternalDataSourceConfiguration.java index 0c68e2a7..6f9446bd 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/ExternalDataSourceConfiguration.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/ExternalDataSourceConfiguration.java @@ -31,6 +31,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; /** * Creates two data sources that use external databases. + * * @author Glenn Renfro */ @Configuration(proxyBeanMethods = false) @@ -52,20 +53,19 @@ public class ExternalDataSourceConfiguration { @Bean(name = "springDataSource") @Primary - public DataSource dataSource(@Qualifier("springDataSourceProperties")DataSourceProperties springDataSourceProperties) { - return DataSourceBuilder.create().driverClassName(springDataSourceProperties.getDriverClassName()). - url(springDataSourceProperties.getUrl()). - password(springDataSourceProperties.getPassword()). - username(springDataSourceProperties.getUsername()). - build(); + public DataSource dataSource( + @Qualifier("springDataSourceProperties") DataSourceProperties springDataSourceProperties) { + return DataSourceBuilder.create().driverClassName(springDataSourceProperties.getDriverClassName()) + .url(springDataSourceProperties.getUrl()).password(springDataSourceProperties.getPassword()) + .username(springDataSourceProperties.getUsername()).build(); } @Bean - public DataSource secondDataSource(@Qualifier("secondDataSourceProperties") DataSourceProperties secondDataSourceProperties) { - return DataSourceBuilder.create().driverClassName(secondDataSourceProperties.getDriverClassName()). - url(secondDataSourceProperties.getUrl()). - password(secondDataSourceProperties.getPassword()). - username(secondDataSourceProperties.getUsername()). - build(); + public DataSource secondDataSource( + @Qualifier("secondDataSourceProperties") DataSourceProperties secondDataSourceProperties) { + return DataSourceBuilder.create().driverClassName(secondDataSourceProperties.getDriverClassName()) + .url(secondDataSourceProperties.getUrl()).password(secondDataSourceProperties.getPassword()) + .username(secondDataSourceProperties.getUsername()).build(); } + } diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/task/SampleCommandLineRunner.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/task/SampleCommandLineRunner.java index dedabbcc..839068d9 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/task/SampleCommandLineRunner.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/task/SampleCommandLineRunner.java @@ -39,7 +39,7 @@ public class SampleCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { - System.out.println("There are " + this.dataSources.size() + - " DataSources within this application"); + System.out.println("There are " + this.dataSources.size() + " DataSources within this application"); } + } diff --git a/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesApplicationTests.java b/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesApplicationTests.java index ca73e232..a8cf5555 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesApplicationTests.java +++ b/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesApplicationTests.java @@ -16,7 +16,6 @@ package io.spring; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -40,10 +39,11 @@ public class MultiDataSourcesApplicationTests { String output = capturedOutput.toString(); assertThat(output.contains("There are 2 DataSources within this application")) - .as("Unable to find CommandLineRunner output: " + output).isTrue(); - assertThat(output.contains("Creating: TaskExecution{")) - .as("Unable to find start task message: " + output).isTrue(); - assertThat(output.contains("Updating: TaskExecution")) - .as("Unable to find update task message: " + output).isTrue(); + .as("Unable to find CommandLineRunner output: " + output).isTrue(); + assertThat(output.contains("Creating: TaskExecution{")).as("Unable to find start task message: " + output) + .isTrue(); + assertThat(output.contains("Updating: TaskExecution")).as("Unable to find update task message: " + output) + .isTrue(); } + } diff --git a/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesExternalApplicationTests.java b/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesExternalApplicationTests.java index 6627c6da..57798c42 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesExternalApplicationTests.java +++ b/spring-cloud-task-samples/multiple-datasources/src/test/java/io/spring/MultiDataSourcesExternalApplicationTests.java @@ -16,7 +16,6 @@ package io.spring; - import java.sql.SQLException; import org.h2.tools.Server; @@ -37,9 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro */ -@ExtendWith({OutputCaptureExtension.class, SpringExtension.class}) +@ExtendWith({ OutputCaptureExtension.class, SpringExtension.class }) @SpringBootTest(classes = { MultiDataSourcesExternalApplicationTests.TaskLauncherConfiguration.class }) public class MultiDataSourcesExternalApplicationTests { + private final static String DATASOURCE_URL; private final static String SECOND_DATASOURCE_URL; @@ -56,35 +56,33 @@ public class MultiDataSourcesExternalApplicationTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; secondRandomPort = TestSocketUtils.findAvailableTcpPort(); - SECOND_DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + SECOND_DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } - @Test public void testTimeStampApp(CapturedOutput capturedOutput) throws Exception { SpringApplication.run(MultipleDataSourcesApplication.class, "--spring.profiles.active=external", - "--spring.datasource.url=" + DATASOURCE_URL, - "--spring.datasource.username=" + DATASOURCE_USER_NAME, - "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, - "--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME, - "--second.datasource.url=" + SECOND_DATASOURCE_URL, - "--second.datasource.username=" + DATASOURCE_USER_NAME, - "--second.datasource.password=" + DATASOURCE_USER_PASSWORD, - "--second.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME); + "--spring.datasource.url=" + DATASOURCE_URL, "--spring.datasource.username=" + DATASOURCE_USER_NAME, + "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, + "--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME, + "--second.datasource.url=" + SECOND_DATASOURCE_URL, + "--second.datasource.username=" + DATASOURCE_USER_NAME, + "--second.datasource.password=" + DATASOURCE_USER_PASSWORD, + "--second.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME); String output = capturedOutput.toString(); assertThat(output.contains("There are 2 DataSources within this application")) - .as("Unable to find CommandLineRunner output: " + output).isTrue(); - assertThat(output.contains("Creating: TaskExecution{")) - .as("Unable to find start task message: " + output).isTrue(); - assertThat(output.contains("Updating: TaskExecution")) - .as("Unable to find update task message: " + output).isTrue(); + .as("Unable to find CommandLineRunner output: " + output).isTrue(); + assertThat(output.contains("Creating: TaskExecution{")).as("Unable to find start task message: " + output) + .isTrue(); + assertThat(output.contains("Updating: TaskExecution")).as("Unable to find update task message: " + output) + .isTrue(); } @Configuration(proxyBeanMethods = false) @@ -99,9 +97,8 @@ public class MultiDataSourcesExternalApplicationTests { Server server = null; try { if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); defaultServer = server; } } @@ -116,9 +113,8 @@ public class MultiDataSourcesExternalApplicationTests { Server server = null; try { if (secondServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(secondRandomPort)) - .start(); + server = Server.createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", + String.valueOf(secondRandomPort)).start(); secondServer = server; } } @@ -127,5 +123,7 @@ public class MultiDataSourcesExternalApplicationTests { } return secondServer; } + } + } diff --git a/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/JobConfiguration.java b/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/JobConfiguration.java index 496b8a67..eee76911 100644 --- a/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/JobConfiguration.java +++ b/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/JobConfiguration.java @@ -63,50 +63,53 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; public class JobConfiguration { private static final int GRID_SIZE = 4; + // @checkstyle:off @Autowired public JobBuilderFactory jobBuilderFactory; + @Autowired public StepBuilderFactory stepBuilderFactory; + @Autowired public DataSource dataSource; + @Autowired public JobRepository jobRepository; + // @checkstyle:on @Autowired private ConfigurableApplicationContext context; + @Autowired private DelegatingResourceLoader resourceLoader; + @Autowired private Environment environment; @Bean public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer, - TaskRepository taskRepository, @Autowired(required = false) ThreadPoolTaskExecutor executor) throws Exception { + TaskRepository taskRepository, @Autowired(required = false) ThreadPoolTaskExecutor executor) + throws Exception { Resource resource = this.resourceLoader - .getResource("maven://io.spring.cloud:partitioned-batch-job:3.0.0-SNAPSHOT"); + .getResource("maven://io.spring.cloud:partitioned-batch-job:3.0.0-SNAPSHOT"); - DeployerPartitionHandler partitionHandler = - new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, + DeployerPartitionHandler partitionHandler = new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep", taskRepository, executor); List commandLineArgs = new ArrayList<>(3); commandLineArgs.add("--spring.profiles.active=worker"); commandLineArgs.add("--spring.cloud.task.initialize-enabled=false"); commandLineArgs.add("--spring.batch.initializer.enabled=false"); - partitionHandler - .setCommandLineArgsProvider(new PassThroughCommandLineArgsProvider(commandLineArgs)); - partitionHandler - .setEnvironmentVariablesProvider(new SimpleEnvironmentVariablesProvider(this.environment)); + partitionHandler.setCommandLineArgsProvider(new PassThroughCommandLineArgsProvider(commandLineArgs)); + partitionHandler.setEnvironmentVariablesProvider(new SimpleEnvironmentVariablesProvider(this.environment)); partitionHandler.setMaxWorkers(2); partitionHandler.setApplicationName("PartitionedBatchJobTask"); return partitionHandler; } - @ConditionalOnProperty( value="io.spring.asynchronous", - havingValue = "true", - matchIfMissing = false) + @ConditionalOnProperty(value = "io.spring.asynchronous", havingValue = "true", matchIfMissing = false) @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); @@ -145,8 +148,7 @@ public class JobConfiguration { @Bean @StepScope - public Tasklet workerTasklet( - final @Value("#{stepExecutionContext['partitionNumber']}") Integer partitionNumber) { + public Tasklet workerTasklet(final @Value("#{stepExecutionContext['partitionNumber']}") Integer partitionNumber) { return new Tasklet() { @Override @@ -160,26 +162,20 @@ public class JobConfiguration { @Bean public Step step1(PartitionHandler partitionHandler) throws Exception { - return this.stepBuilderFactory.get("step1") - .partitioner(workerStep().getName(), partitioner()) - .step(workerStep()) - .partitionHandler(partitionHandler) - .build(); + return this.stepBuilderFactory.get("step1").partitioner(workerStep().getName(), partitioner()) + .step(workerStep()).partitionHandler(partitionHandler).build(); } @Bean public Step workerStep() { - return this.stepBuilderFactory.get("workerStep") - .tasklet(workerTasklet(null)) - .build(); + return this.stepBuilderFactory.get("workerStep").tasklet(workerTasklet(null)).build(); } @Bean @Profile("!worker") public Job partitionedJob(PartitionHandler partitionHandler) throws Exception { Random random = new Random(); - return this.jobBuilderFactory.get("partitionedJob" + random.nextInt()) - .start(step1(partitionHandler)) - .build(); + return this.jobBuilderFactory.get("partitionedJob" + random.nextInt()).start(step1(partitionHandler)).build(); } + } diff --git a/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/PartitionedBatchJobApplication.java b/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/PartitionedBatchJobApplication.java index cf49df3e..dec2258f 100644 --- a/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/PartitionedBatchJobApplication.java +++ b/spring-cloud-task-samples/partitioned-batch-job/src/main/java/io/spring/PartitionedBatchJobApplication.java @@ -29,4 +29,5 @@ public class PartitionedBatchJobApplication { public static void main(String[] args) { SpringApplication.run(PartitionedBatchJobApplication.class, args); } + } diff --git a/spring-cloud-task-samples/partitioned-batch-job/src/test/java/org/springframework/cloud/task/partitioner/TaskPartitionerTests.java b/spring-cloud-task-samples/partitioned-batch-job/src/test/java/org/springframework/cloud/task/partitioner/TaskPartitionerTests.java index 1450dd58..0c87e928 100644 --- a/spring-cloud-task-samples/partitioned-batch-job/src/test/java/org/springframework/cloud/task/partitioner/TaskPartitionerTests.java +++ b/spring-cloud-task-samples/partitioned-batch-job/src/test/java/org/springframework/cloud/task/partitioner/TaskPartitionerTests.java @@ -46,22 +46,27 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = {TaskPartitionerTests.TaskLauncherConfiguration.class}) +@SpringBootTest(classes = { TaskPartitionerTests.TaskLauncherConfiguration.class }) public class TaskPartitionerTests { private final static String DATASOURCE_USER_NAME = "SA"; + private final static String DATASOURCE_USER_PASSWORD = ""; + private final static String DATASOURCE_DRIVER_CLASS_NAME = "org.h2.Driver"; + private static String DATASOURCE_URL; + private static int randomPort; static { randomPort = TestSocketUtils.findAvailableTcpPort(); DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" - + "DB_CLOSE_ON_EXIT=FALSE"; + + "DB_CLOSE_ON_EXIT=FALSE"; } private TaskExplorer taskExplorer; + @Autowired private DataSource dataSource; @@ -100,16 +105,12 @@ public class TaskPartitionerTests { app.setDefaultProperties(properties); app.run(); - Page taskExecutions = this.taskExplorer - .findAll(PageRequest.of(0, 10)); - assertThat(taskExecutions.getTotalElements()).as("Five rows are expected") - .isEqualTo(5); - assertThat(this.taskExplorer - .getTaskExecutionCountByTaskName("PartitionedBatchJobTask")) - .as("Only One master is expected").isEqualTo(1); + Page taskExecutions = this.taskExplorer.findAll(PageRequest.of(0, 10)); + assertThat(taskExecutions.getTotalElements()).as("Five rows are expected").isEqualTo(5); + assertThat(this.taskExplorer.getTaskExecutionCountByTaskName("PartitionedBatchJobTask")) + .as("Only One master is expected").isEqualTo(1); for (TaskExecution taskExecution : taskExecutions) { - assertThat(taskExecution.getExitCode() - .intValue()).as("return code should be 0").isEqualTo(0); + assertThat(taskExecution.getExitCode().intValue()).as("return code should be 0").isEqualTo(0); } } @@ -120,10 +121,8 @@ public class TaskPartitionerTests { public org.h2.tools.Server initH2TCPServer() { Server server; try { - server = Server - .createTcpServer("-tcp", "-ifNotExists", "-tcpAllowOthers", "-tcpPort", String - .valueOf(randomPort)) - .start(); + server = Server.createTcpServer("-tcp", "-ifNotExists", "-tcpAllowOthers", "-tcpPort", + String.valueOf(randomPort)).start(); } catch (SQLException e) { throw new IllegalStateException(e); @@ -140,6 +139,7 @@ public class TaskPartitionerTests { dataSource.setPassword(DATASOURCE_USER_PASSWORD); return dataSource; } + } } diff --git a/spring-cloud-task-samples/single-step-batch-job/src/main/java/io/spring/SingleStepBatchJobApplication.java b/spring-cloud-task-samples/single-step-batch-job/src/main/java/io/spring/SingleStepBatchJobApplication.java index 6174653f..7bbe2fd9 100644 --- a/spring-cloud-task-samples/single-step-batch-job/src/main/java/io/spring/SingleStepBatchJobApplication.java +++ b/spring-cloud-task-samples/single-step-batch-job/src/main/java/io/spring/SingleStepBatchJobApplication.java @@ -29,4 +29,5 @@ public class SingleStepBatchJobApplication { public static void main(String[] args) { SpringApplication.run(SingleStepBatchJobApplication.class, args); } + } diff --git a/spring-cloud-task-samples/single-step-batch-job/src/test/java/io/spring/BatchJobApplicationTests.java b/spring-cloud-task-samples/single-step-batch-job/src/test/java/io/spring/BatchJobApplicationTests.java index a485c012..7b82a941 100644 --- a/spring-cloud-task-samples/single-step-batch-job/src/test/java/io/spring/BatchJobApplicationTests.java +++ b/spring-cloud-task-samples/single-step-batch-job/src/test/java/io/spring/BatchJobApplicationTests.java @@ -64,8 +64,8 @@ public class BatchJobApplicationTests { static { randomPort = TestSocketUtils.findAvailableTcpPort(); - DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort - + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + "DB_CLOSE_ON_EXIT=FALSE"; + DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" + + "DB_CLOSE_ON_EXIT=FALSE"; } private File outputFile; @@ -90,45 +90,36 @@ public class BatchJobApplicationTests { @Test public void testFileReaderJdbcWriter() throws Exception { - getSpringApplication().run(SingleStepBatchJobApplication.class, - "--spring.profiles.active=ffreader,jdbcwriter", - "--spring.datasource.username=" + DATASOURCE_USER_NAME, - "--spring.datasource.url=" + DATASOURCE_URL, - "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, - "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, - "foo=testFileReaderJdbcWriter"); + getSpringApplication().run(SingleStepBatchJobApplication.class, "--spring.profiles.active=ffreader,jdbcwriter", + "--spring.datasource.username=" + DATASOURCE_USER_NAME, "--spring.datasource.url=" + DATASOURCE_URL, + "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, + "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, "foo=testFileReaderJdbcWriter"); validateDBResult(); } @Test public void testJdbcReaderJdbcWriter() throws Exception { getSpringApplication().run(SingleStepBatchJobApplication.class, - "--spring.profiles.active=jdbcreader,jdbcwriter", - "--spring.datasource.username=" + DATASOURCE_USER_NAME, - "--spring.datasource.url=" + DATASOURCE_URL, - "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, - "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, - "foo=testJdbcReaderJdbcWriter"); + "--spring.profiles.active=jdbcreader,jdbcwriter", + "--spring.datasource.username=" + DATASOURCE_USER_NAME, "--spring.datasource.url=" + DATASOURCE_URL, + "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, + "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, "foo=testJdbcReaderJdbcWriter"); validateDBResult(); } @Test public void testJdbcReaderFlatfileWriter() throws Exception { - getSpringApplication().run(SingleStepBatchJobApplication.class, - "--spring.profiles.active=jdbcreader,ffwriter", - "--spring.datasource.username=" + DATASOURCE_USER_NAME, - "--spring.datasource.url=" + DATASOURCE_URL, - "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, - "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, - "foo=testJdbcReaderFlatfileWriter"); + getSpringApplication().run(SingleStepBatchJobApplication.class, "--spring.profiles.active=jdbcreader,ffwriter", + "--spring.datasource.username=" + DATASOURCE_USER_NAME, "--spring.datasource.url=" + DATASOURCE_URL, + "--spring.datasource.driver-class-name=" + DATASOURCE_DRIVER_CLASS_NAME, + "--spring.datasource.password=" + DATASOURCE_USER_PASSWORD, "foo=testJdbcReaderFlatfileWriter"); validateFileResult(); } @Test public void testFileReaderFileWriter() throws Exception { - getSpringApplication().run(SingleStepBatchJobApplication.class, - "--spring.profiles.active=ffreader,ffwriter", - "foo=testFileReaderFileWriter"); + getSpringApplication().run(SingleStepBatchJobApplication.class, "--spring.profiles.active=ffreader,ffwriter", + "foo=testFileReaderFileWriter"); validateFileResult(); } @@ -136,36 +127,33 @@ public class BatchJobApplicationTests { Server server; if (defaultServer == null) { - server = Server.createTcpServer("-ifNotExists", "-tcp", - "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + server = Server + .createTcpServer("-ifNotExists", "-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) + .start(); defaultServer = server; DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(DATASOURCE_DRIVER_CLASS_NAME); dataSource.setUrl(DATASOURCE_URL); dataSource.setUsername(DATASOURCE_USER_NAME); dataSource.setPassword(DATASOURCE_USER_PASSWORD); - ClassPathResource setupResource = new ClassPathResource( - "schema-h2.sql"); - ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator( - setupResource); + ClassPathResource setupResource = new ClassPathResource("schema-h2.sql"); + ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(setupResource); resourceDatabasePopulator.execute(dataSource); } return defaultServer; } - private void validateFileResult() throws Exception{ -// AssertFile.assertLineCount(6, new FileSystemResource("./result.txt")); -// AssertFile.assertFileEquals(new ClassPathResource("testresult.txt"), -// new FileSystemResource(this.outputFile)); + private void validateFileResult() throws Exception { + // AssertFile.assertLineCount(6, new FileSystemResource("./result.txt")); + // AssertFile.assertFileEquals(new ClassPathResource("testresult.txt"), + // new FileSystemResource(this.outputFile)); } private void validateDBResult() { DataSource dataSource = getDataSource(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - List> result = jdbcTemplate - .queryForList("SELECT item_name FROM item ORDER BY item_name"); + List> result = jdbcTemplate.queryForList("SELECT item_name FROM item ORDER BY item_name"); assertThat(result.size()).isEqualTo(6); assertThat(result.get(0).get("item_name")).isEqualTo("Job"); @@ -184,6 +172,7 @@ public class BatchJobApplicationTests { dataSourceBuilder.password(DATASOURCE_USER_PASSWORD); return dataSourceBuilder.build(); } + private SpringApplication getSpringApplication() { SpringApplication springApplication = new SpringApplication(); Map properties = new HashMap<>(); diff --git a/spring-cloud-task-samples/task-events/src/main/java/io/spring/TaskEventsApplication.java b/spring-cloud-task-samples/task-events/src/main/java/io/spring/TaskEventsApplication.java index ff7a2ef9..7f954d83 100644 --- a/spring-cloud-task-samples/task-events/src/main/java/io/spring/TaskEventsApplication.java +++ b/spring-cloud-task-samples/task-events/src/main/java/io/spring/TaskEventsApplication.java @@ -43,5 +43,7 @@ public class TaskEventsApplication { } }; } + } + } diff --git a/spring-cloud-task-samples/task-observations/src/main/java/io/spring/taskobservations/ObservationConfiguration.java b/spring-cloud-task-samples/task-observations/src/main/java/io/spring/taskobservations/ObservationConfiguration.java index fe8e21a6..0ce038ad 100644 --- a/spring-cloud-task-samples/task-observations/src/main/java/io/spring/taskobservations/ObservationConfiguration.java +++ b/spring-cloud-task-samples/task-observations/src/main/java/io/spring/taskobservations/ObservationConfiguration.java @@ -23,8 +23,10 @@ import org.springframework.context.annotation.Configuration; @Configuration public class ObservationConfiguration { + @Bean public SimpleMeterRegistry meterRegistry() { return new SimpleMeterRegistry(); } + } diff --git a/spring-cloud-task-samples/task-observations/src/test/java/io/spring/taskobservations/TaskObservationsApplicationTests.java b/spring-cloud-task-samples/task-observations/src/test/java/io/spring/taskobservations/TaskObservationsApplicationTests.java index 938f32fe..b163eaa4 100644 --- a/spring-cloud-task-samples/task-observations/src/test/java/io/spring/taskobservations/TaskObservationsApplicationTests.java +++ b/spring-cloud-task-samples/task-observations/src/test/java/io/spring/taskobservations/TaskObservationsApplicationTests.java @@ -32,12 +32,12 @@ class TaskObservationsApplicationTests { @Test void contextLoads(CapturedOutput output) { String result = output.getAll(); - assertThat(result).contains("spring.cloud.task(TIMER)[application='task-observations-application-58', " + - "error='none', service='task-observations-application', " + - "spring.cloud.task.execution.id='1', spring.cloud.task.exit.code='0', " + - "spring.cloud.task.external.execution.id='unknown', spring.cloud.task.name='taskmetrics', " + - "spring.cloud.task.parent.execution.id='unknown', spring.cloud.task.status='success']; " + - "count=1.0, total_time="); + assertThat(result).contains("spring.cloud.task(TIMER)[application='task-observations-application-58', " + + "error='none', service='task-observations-application', " + + "spring.cloud.task.execution.id='1', spring.cloud.task.exit.code='0', " + + "spring.cloud.task.external.execution.id='unknown', spring.cloud.task.name='taskmetrics', " + + "spring.cloud.task.parent.execution.id='unknown', spring.cloud.task.status='success']; " + + "count=1.0, total_time="); } } diff --git a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessor.java b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessor.java index 1d02b1bb..d19db1cf 100644 --- a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessor.java +++ b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessor.java @@ -48,30 +48,25 @@ public class TaskProcessor { String message = messagePayload.getPayload(); Map properties = new HashMap<>(); if (StringUtils.hasText(this.processorProperties.getDataSourceUrl())) { - properties - .put("spring_datasource_url", this.processorProperties - .getDataSourceUrl()); + properties.put("spring_datasource_url", this.processorProperties.getDataSourceUrl()); } - if (StringUtils - .hasText(this.processorProperties.getDataSourceDriverClassName())) { - properties.put("spring_datasource_driverClassName", this.processorProperties - .getDataSourceDriverClassName()); + if (StringUtils.hasText(this.processorProperties.getDataSourceDriverClassName())) { + properties.put("spring_datasource_driverClassName", + this.processorProperties.getDataSourceDriverClassName()); } if (StringUtils.hasText(this.processorProperties.getDataSourceUserName())) { - properties.put("spring_datasource_username", this.processorProperties - .getDataSourceUserName()); + properties.put("spring_datasource_username", this.processorProperties.getDataSourceUserName()); } if (StringUtils.hasText(this.processorProperties.getDataSourcePassword())) { - properties.put("spring_datasource_password", this.processorProperties - .getDataSourcePassword()); + properties.put("spring_datasource_password", this.processorProperties.getDataSourcePassword()); } properties.put("payload", message); - TaskLaunchRequest request = new TaskLaunchRequest( - this.processorProperties.getUri(), null, properties, null, - this.processorProperties.getApplicationName()); + TaskLaunchRequest request = new TaskLaunchRequest(this.processorProperties.getUri(), null, properties, null, + this.processorProperties.getApplicationName()); return MessageBuilder.withPayload(request).build(); }; } + } diff --git a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorApplication.java b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorApplication.java index 9ed1f789..7698bc1f 100644 --- a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorApplication.java +++ b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorApplication.java @@ -28,4 +28,5 @@ public class TaskProcessorApplication { public static void main(String[] args) { SpringApplication.run(TaskProcessorApplication.class, args); } + } diff --git a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorProperties.java b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorProperties.java index 955c59dd..3adc0841 100644 --- a/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorProperties.java +++ b/spring-cloud-task-samples/taskprocessor/src/main/java/io/spring/TaskProcessorProperties.java @@ -25,8 +25,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; public class TaskProcessorProperties { private static final String DEFAULT_URI = "maven://org.springframework.cloud.task.app:" - + "timestamp-task:jar:1.0.1.RELEASE"; - + + "timestamp-task:jar:1.0.1.RELEASE"; private String uri = DEFAULT_URI; @@ -40,7 +39,6 @@ public class TaskProcessorProperties { private String applicationName; - public String getDataSourceUrl() { return this.dataSourceUrl; } @@ -88,4 +86,5 @@ public class TaskProcessorProperties { public void setApplicationName(String applicationName) { this.applicationName = applicationName; } + } diff --git a/spring-cloud-task-samples/taskprocessor/src/test/java/io/spring/TaskProcessorApplicationTests.java b/spring-cloud-task-samples/taskprocessor/src/test/java/io/spring/TaskProcessorApplicationTests.java index d6caaa5c..472f6573 100644 --- a/spring-cloud-task-samples/taskprocessor/src/test/java/io/spring/TaskProcessorApplicationTests.java +++ b/spring-cloud-task-samples/taskprocessor/src/test/java/io/spring/TaskProcessorApplicationTests.java @@ -23,7 +23,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterEach; @@ -53,6 +52,7 @@ public class TaskProcessorApplicationTests { private static final String DEFAULT_PAYLOAD = "hello"; private final ObjectMapper objectMapper = new ObjectMapper(); + private ConfigurableApplicationContext applicationContext; @BeforeEach @@ -72,22 +72,19 @@ public class TaskProcessorApplicationTests { Map properties = new HashMap(); properties.put("payload", DEFAULT_PAYLOAD); TaskLaunchRequest expectedRequest = new TaskLaunchRequest( - "maven://org.springframework.cloud.task.app:" - + "timestamp-task:jar:1.0.1.RELEASE", null, properties, - null, null); + "maven://org.springframework.cloud.task.app:" + "timestamp-task:jar:1.0.1.RELEASE", null, properties, + null, null); List> result = testListener("output", 1); TaskLaunchRequest tlq = objectMapper.readValue(result.get(0).getPayload(), TaskLaunchRequest.class); assertThat(tlq).isEqualTo(expectedRequest); } - private List> testListener(String bindingName, int numberToRead) { List> results = new ArrayList<>(); this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(TaskProcessorTestApplication.class)).web(WebApplicationType.NONE) - .run(); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(TaskProcessorTestApplication.class)) + .web(WebApplicationType.NONE).run(); InputDestination input = this.applicationContext.getBean(InputDestination.class); OutputDestination target = this.applicationContext.getBean(OutputDestination.class); @@ -99,7 +96,9 @@ public class TaskProcessorApplicationTests { } @SpringBootApplication - @Import({TaskProcessor.class}) + @Import({ TaskProcessor.class }) public static class TaskProcessorTestApplication { + } + } diff --git a/spring-cloud-task-samples/tasksink/src/main/java/io/spring/TaskSinkApplication.java b/spring-cloud-task-samples/tasksink/src/main/java/io/spring/TaskSinkApplication.java index 20327b70..ba18ba07 100644 --- a/spring-cloud-task-samples/tasksink/src/main/java/io/spring/TaskSinkApplication.java +++ b/spring-cloud-task-samples/tasksink/src/main/java/io/spring/TaskSinkApplication.java @@ -32,4 +32,5 @@ public class TaskSinkApplication { public static void main(String[] args) { SpringApplication.run(TaskSinkApplication.class, args); } + } diff --git a/spring-cloud-task-samples/tasksink/src/test/java/io/spring/TaskSinkApplicationTests.java b/spring-cloud-task-samples/tasksink/src/test/java/io/spring/TaskSinkApplicationTests.java index 879d2af0..ca4c3766 100644 --- a/spring-cloud-task-samples/tasksink/src/test/java/io/spring/TaskSinkApplicationTests.java +++ b/spring-cloud-task-samples/tasksink/src/test/java/io/spring/TaskSinkApplicationTests.java @@ -53,30 +53,26 @@ public class TaskSinkApplicationTests { @Test public void testLaunch() { - TaskLauncher testTaskLauncher = - this.context.getBean(TaskLauncher.class); + TaskLauncher testTaskLauncher = this.context.getBean(TaskLauncher.class); Map properties = new HashMap(); properties.put("server.port", "0"); TaskLaunchRequest request = new TaskLaunchRequest( - "maven://org.springframework.cloud.task.app:" - + "timestamp-task:jar:1.0.1.RELEASE", null, properties, - null, null); + "maven://org.springframework.cloud.task.app:" + "timestamp-task:jar:1.0.1.RELEASE", null, properties, + null, null); GenericMessage message = new GenericMessage<>(request); this.streamBridge.send("taskLauncherSink-in-0", message); - ArgumentCaptor deploymentRequest = ArgumentCaptor - .forClass(AppDeploymentRequest.class); + ArgumentCaptor deploymentRequest = ArgumentCaptor.forClass(AppDeploymentRequest.class); verify(testTaskLauncher).launch(deploymentRequest.capture()); AppDeploymentRequest actualRequest = deploymentRequest.getValue(); assertThat(actualRequest.getCommandlineArguments().isEmpty()).isTrue(); - assertThat(actualRequest.getDefinition().getProperties() - .get("server.port")).isEqualTo("0"); + assertThat(actualRequest.getDefinition().getProperties().get("server.port")).isEqualTo("0"); assertThat(actualRequest.getResource().toString() - .contains("org.springframework.cloud.task.app:timestamp-task:jar:1.0.1.RELEASE")) - .isTrue(); + .contains("org.springframework.cloud.task.app:timestamp-task:jar:1.0.1.RELEASE")).isTrue(); } + } diff --git a/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TaskApplication.java b/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TaskApplication.java index 9ec332e6..2869a1c4 100644 --- a/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TaskApplication.java +++ b/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TaskApplication.java @@ -16,7 +16,6 @@ package org.springframework.cloud.task.timestamp; - import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @@ -37,7 +36,7 @@ import org.springframework.context.annotation.Bean; */ @EnableTask @SpringBootApplication -@EnableConfigurationProperties({TimestampTaskProperties.class}) +@EnableConfigurationProperties({ TimestampTaskProperties.class }) public class TaskApplication { private static final Log logger = LogFactory.getLog(TaskApplication.class); @@ -64,5 +63,7 @@ public class TaskApplication { DateFormat dateFormat = new SimpleDateFormat(this.config.getFormat()); logger.info(dateFormat.format(new Date())); } + } + } diff --git a/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TimestampTaskProperties.java b/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TimestampTaskProperties.java index 48f2c57d..20fe8793 100644 --- a/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TimestampTaskProperties.java +++ b/spring-cloud-task-samples/timestamp/src/main/java/org/springframework/cloud/task/timestamp/TimestampTaskProperties.java @@ -38,4 +38,5 @@ public class TimestampTaskProperties { public void setFormat(String format) { this.format = format; } + } diff --git a/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TaskApplicationTests.java b/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TaskApplicationTests.java index 740540d5..10abfebb 100644 --- a/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TaskApplicationTests.java +++ b/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TaskApplicationTests.java @@ -36,26 +36,23 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(OutputCaptureExtension.class) public class TaskApplicationTests { - @Test public void testTimeStampApp(CapturedOutput capturedOutput) throws Exception { final String TEST_DATE_DOTS = "......."; final String CREATE_TASK_MESSAGE = "Creating: TaskExecution{executionId="; final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution with executionId="; final String EXIT_CODE_MESSAGE = "with the following {exitCode=0"; - String[] args = {"--format=yyyy" + TEST_DATE_DOTS}; + String[] args = { "--format=yyyy" + TEST_DATE_DOTS }; SpringApplication.run(TaskApplication.class, args); String output = capturedOutput.toString(); - assertThat(output.contains(TEST_DATE_DOTS)) - .as("Unable to find the timestamp: " + output).isTrue(); - assertThat(output.contains(CREATE_TASK_MESSAGE)) - .as("Test results do not show create task message: " + output).isTrue(); - assertThat(output.contains(UPDATE_TASK_MESSAGE)) - .as("Test results do not show success message: " + output).isTrue(); - assertThat(output.contains(EXIT_CODE_MESSAGE)) - .as("Test results have incorrect exit code: " + output).isTrue(); + assertThat(output.contains(TEST_DATE_DOTS)).as("Unable to find the timestamp: " + output).isTrue(); + assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output) + .isTrue(); + assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output) + .isTrue(); + assertThat(output.contains(EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output).isTrue(); String taskTitle = "Demo Timestamp Task"; Pattern pattern = Pattern.compile(taskTitle); @@ -64,7 +61,7 @@ public class TaskApplicationTests { while (matcher.find()) { count++; } - assertThat(count).as("The number of task titles did not match expected: ") - .isEqualTo(1); + assertThat(count).as("The number of task titles did not match expected: ").isEqualTo(1); } + } diff --git a/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TimestampTaskPropertiesTests.java b/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TimestampTaskPropertiesTests.java index 48317691..d9317a53 100644 --- a/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TimestampTaskPropertiesTests.java +++ b/spring-cloud-task-samples/timestamp/src/test/java/org/springframework/cloud/task/timestamp/TimestampTaskPropertiesTests.java @@ -16,7 +16,6 @@ package org.springframework.cloud.task.timestamp; - import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -39,8 +38,7 @@ public class TimestampTaskPropertiesTests { testPropertyValues.applyTo(context); context.register(Conf.class); context.refresh(); - TimestampTaskProperties properties = context - .getBean(TimestampTaskProperties.class); + TimestampTaskProperties properties = context.getBean(TimestampTaskProperties.class); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { properties.getFormat(); }); @@ -51,10 +49,9 @@ public class TimestampTaskPropertiesTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Conf.class); context.refresh(); - TimestampTaskProperties properties = context - .getBean(TimestampTaskProperties.class); + TimestampTaskProperties properties = context.getBean(TimestampTaskProperties.class); assertThat(properties.getFormat()).as("result does not match default format.") - .isEqualTo("yyyy-MM-dd HH:mm:ss.SSS"); + .isEqualTo("yyyy-MM-dd HH:mm:ss.SSS"); } @Test @@ -63,15 +60,15 @@ public class TimestampTaskPropertiesTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Conf.class); context.refresh(); - TimestampTaskProperties properties = context - .getBean(TimestampTaskProperties.class); + TimestampTaskProperties properties = context.getBean(TimestampTaskProperties.class); properties.setFormat(FORMAT); - assertThat(properties.getFormat()).as("result does not match established format.") - .isEqualTo(FORMAT); + assertThat(properties.getFormat()).as("result does not match established format.").isEqualTo(FORMAT); } @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(TimestampTaskProperties.class) static class Conf { + } + } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/BatchEventAutoConfiguration.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/BatchEventAutoConfiguration.java index 7c499f8a..a5a58e8a 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/BatchEventAutoConfiguration.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/BatchEventAutoConfiguration.java @@ -64,8 +64,8 @@ import org.springframework.context.annotation.Lazy; @ConditionalOnClass(Job.class) @ConditionalOnBean({ Job.class, TaskLifecycleListener.class }) // @checkstyle:off -@ConditionalOnProperty(prefix = "spring.cloud.task.batch.events", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.cloud.task.batch.events", name = "enabled", havingValue = "true", + matchIfMissing = true) // @checkstyle:on @AutoConfigureAfter(SimpleTaskAutoConfiguration.class) public class BatchEventAutoConfiguration { @@ -121,88 +121,85 @@ public class BatchEventAutoConfiguration { @ConditionalOnExpression("T(org.springframework.util.StringUtils).isEmpty('${spring.batch.job.jobName:}')") public static class JobExecutionListenerConfiguration { - @Autowired private TaskEventProperties taskEventProperties; // @checkstyle:off @Bean @Lazy - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.job-execution", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.job-execution", name = "enabled", + havingValue = "true", matchIfMissing = true) // @checkstyle:on - public JobExecutionListener jobExecutionEventsListener(MessagePublisher messagePublisher, TaskEventProperties properties) { - return new EventEmittingJobExecutionListener( - messagePublisher, + public JobExecutionListener jobExecutionEventsListener(MessagePublisher messagePublisher, + TaskEventProperties properties) { + return new EventEmittingJobExecutionListener(messagePublisher, this.taskEventProperties.getJobExecutionOrder(), properties); } // @checkstyle:off @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.step-execution", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.step-execution", name = "enabled", + havingValue = "true", matchIfMissing = true) // @checkstyle:on - public StepExecutionListener stepExecutionEventsListener(MessagePublisher messagePublisher, TaskEventProperties properties) { - return new EventEmittingStepExecutionListener( - messagePublisher, + public StepExecutionListener stepExecutionEventsListener(MessagePublisher messagePublisher, + TaskEventProperties properties) { + return new EventEmittingStepExecutionListener(messagePublisher, this.taskEventProperties.getStepExecutionOrder(), properties); } // @checkstyle:off @Bean @Lazy - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.chunk", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.chunk", name = "enabled", havingValue = "true", + matchIfMissing = true) // @checkstyle:on - public EventEmittingChunkListener chunkEventsListener(MessagePublisher messagePublisher, TaskEventProperties properties) { - return new EventEmittingChunkListener(messagePublisher, - this.taskEventProperties.getChunkOrder(), properties); + public EventEmittingChunkListener chunkEventsListener(MessagePublisher messagePublisher, + TaskEventProperties properties) { + return new EventEmittingChunkListener(messagePublisher, this.taskEventProperties.getChunkOrder(), + properties); } // @checkstyle:off @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-read", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-read", name = "enabled", + havingValue = "true", matchIfMissing = true) // @checkstyle:on - public ItemReadListener itemReadEventsListener(MessagePublisher messagePublisher, TaskEventProperties properties) { - return new EventEmittingItemReadListener( - messagePublisher, - this.taskEventProperties.getItemReadOrder(), properties); + public ItemReadListener itemReadEventsListener(MessagePublisher messagePublisher, + TaskEventProperties properties) { + return new EventEmittingItemReadListener(messagePublisher, this.taskEventProperties.getItemReadOrder(), + properties); } // @checkstyle:off @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-write", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-write", name = "enabled", + havingValue = "true", matchIfMissing = true) // @checkstyle:on public ItemWriteListener itemWriteEventsListener(MessagePublisher messagePublisher, - TaskEventProperties properties) { - return new EventEmittingItemWriteListener( - messagePublisher, - this.taskEventProperties.getItemWriteOrder(), properties); + TaskEventProperties properties) { + return new EventEmittingItemWriteListener(messagePublisher, this.taskEventProperties.getItemWriteOrder(), + properties); } // @checkstyle:off @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-process", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-process", name = "enabled", + havingValue = "true", matchIfMissing = true) // @checkstyle:on public ItemProcessListener itemProcessEventsListener(MessagePublisher messagePublisher, - TaskEventProperties properties) { - return new EventEmittingItemProcessListener( - messagePublisher, + TaskEventProperties properties) { + return new EventEmittingItemProcessListener(messagePublisher, this.taskEventProperties.getItemProcessOrder(), properties); } // @checkstyle:off @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.skip", - name = "enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.skip", name = "enabled", havingValue = "true", + matchIfMissing = true) // @checkstyle:on - public SkipListener skipEventsListener(MessagePublisher messagePublisher, - TaskEventProperties properties) { - return new EventEmittingSkipListener(messagePublisher, - this.taskEventProperties.getItemProcessOrder(), properties); + public SkipListener skipEventsListener(MessagePublisher messagePublisher, TaskEventProperties properties) { + return new EventEmittingSkipListener(messagePublisher, this.taskEventProperties.getItemProcessOrder(), + properties); } @Bean diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingChunkListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingChunkListener.java index b794d97b..9920484a 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingChunkListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingChunkListener.java @@ -55,14 +55,12 @@ public class EventEmittingChunkListener implements ChunkListener, Ordered { @Override public void beforeChunk(ChunkContext context) { - this.messagePublisher.publish(this.properties.getChunkEventBindingName(), - "Before Chunk Processing"); + this.messagePublisher.publish(this.properties.getChunkEventBindingName(), "Before Chunk Processing"); } @Override public void afterChunk(ChunkContext context) { - this.messagePublisher.publish(this.properties.getChunkEventBindingName(), - "After Chunk Processing"); + this.messagePublisher.publish(this.properties.getChunkEventBindingName(), "After Chunk Processing"); } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemProcessListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemProcessListener.java index f78719e0..0bb43883 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemProcessListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemProcessListener.java @@ -43,8 +43,7 @@ import org.springframework.util.Assert; */ public class EventEmittingItemProcessListener implements ItemProcessListener, Ordered { - private static final Log logger = LogFactory - .getLog(EventEmittingItemProcessListener.class); + private static final Log logger = LogFactory.getLog(EventEmittingItemProcessListener.class); private MessagePublisher messagePublisher; @@ -59,7 +58,8 @@ public class EventEmittingItemProcessListener implements ItemProcessListener, Or this.properties = properties; } - public EventEmittingItemProcessListener(MessagePublisher messagePublisher, int order, TaskEventProperties properties) { + public EventEmittingItemProcessListener(MessagePublisher messagePublisher, int order, + TaskEventProperties properties) { this(messagePublisher, properties); this.order = order; } @@ -74,10 +74,12 @@ public class EventEmittingItemProcessListener implements ItemProcessListener, Or this.messagePublisher.publish(this.properties.getItemProcessEventBindingName(), "1 item was filtered"); } else if (item.equals(result)) { - this.messagePublisher.publish(this.properties.getItemProcessEventBindingName(), "item equaled result after processing"); + this.messagePublisher.publish(this.properties.getItemProcessEventBindingName(), + "item equaled result after processing"); } else { - this.messagePublisher.publish(this.properties.getItemProcessEventBindingName(), "item did not equal result after processing"); + this.messagePublisher.publish(this.properties.getItemProcessEventBindingName(), + "item did not equal result after processing"); } } @@ -86,9 +88,8 @@ public class EventEmittingItemProcessListener implements ItemProcessListener, Or if (logger.isDebugEnabled()) { logger.debug("Executing onProcessError: " + e.getMessage(), e); } - this.messagePublisher.publishWithThrowableHeader( - this.properties.getItemProcessEventBindingName(), - "Exception while item was being processed", e.getMessage()); + this.messagePublisher.publishWithThrowableHeader(this.properties.getItemProcessEventBindingName(), + "Exception while item was being processed", e.getMessage()); } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemReadListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemReadListener.java index ec51e21d..1e541c37 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemReadListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemReadListener.java @@ -40,8 +40,7 @@ import org.springframework.util.Assert; */ public class EventEmittingItemReadListener implements ItemReadListener, Ordered { - private static final Log logger = LogFactory - .getLog(EventEmittingItemReadListener.class); + private static final Log logger = LogFactory.getLog(EventEmittingItemReadListener.class); private int order = Ordered.LOWEST_PRECEDENCE; @@ -56,8 +55,7 @@ public class EventEmittingItemReadListener implements ItemReadListener, Ordered this.messagePublisher = messagePublisher; } - public EventEmittingItemReadListener(MessagePublisher messagePublisher, - int order, TaskEventProperties properties) { + public EventEmittingItemReadListener(MessagePublisher messagePublisher, int order, TaskEventProperties properties) { this(messagePublisher, properties); this.order = order; } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemWriteListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemWriteListener.java index d962a0f8..9900fc0d 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemWriteListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingItemWriteListener.java @@ -41,8 +41,7 @@ import org.springframework.util.Assert; */ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordered { - private static final Log logger = LogFactory - .getLog(EventEmittingItemWriteListener.class); + private static final Log logger = LogFactory.getLog(EventEmittingItemWriteListener.class); private int order = Ordered.LOWEST_PRECEDENCE; @@ -58,7 +57,8 @@ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordere this.properties = properties; } - public EventEmittingItemWriteListener(MessagePublisher messagePublisher, int order, TaskEventProperties properties) { + public EventEmittingItemWriteListener(MessagePublisher messagePublisher, int order, + TaskEventProperties properties) { this(messagePublisher, properties); this.order = order; } @@ -66,7 +66,7 @@ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordere @Override public void beforeWrite(List items) { this.messagePublisher.publish(this.properties.getItemWriteEventBindingName(), - items.size() + " items to be written."); + items.size() + " items to be written."); } @Override @@ -75,7 +75,7 @@ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordere logger.debug("Executing afterWrite: " + items); } this.messagePublisher.publish(this.properties.getItemWriteEventBindingName(), - items.size() + " items have been written."); + items.size() + " items have been written."); } @Override @@ -83,10 +83,9 @@ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordere if (logger.isDebugEnabled()) { logger.debug("Executing onWriteError: " + exception.getMessage(), exception); } - String payload = "Exception while " + items.size() - + " items are attempted to be written."; - this.messagePublisher.publishWithThrowableHeader( - this.properties.getItemWriteEventBindingName(), payload, exception.getMessage()); + String payload = "Exception while " + items.size() + " items are attempted to be written."; + this.messagePublisher.publishWithThrowableHeader(this.properties.getItemWriteEventBindingName(), payload, + exception.getMessage()); } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingJobExecutionListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingJobExecutionListener.java index 26561885..036ddf4b 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingJobExecutionListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingJobExecutionListener.java @@ -47,19 +47,22 @@ public class EventEmittingJobExecutionListener implements JobExecutionListener, this.properties = properties; } - public EventEmittingJobExecutionListener(MessagePublisher messagePublisher, int order, TaskEventProperties properties) { + public EventEmittingJobExecutionListener(MessagePublisher messagePublisher, int order, + TaskEventProperties properties) { this(messagePublisher, properties); this.order = order; } @Override public void beforeJob(JobExecution jobExecution) { - this.messagePublisher.publish(properties.getJobExecutionEventBindingName(), new JobExecutionEvent(jobExecution)); + this.messagePublisher.publish(properties.getJobExecutionEventBindingName(), + new JobExecutionEvent(jobExecution)); } @Override public void afterJob(JobExecution jobExecution) { - this.messagePublisher.publish(properties.getJobExecutionEventBindingName(), new JobExecutionEvent(jobExecution)); + this.messagePublisher.publish(properties.getJobExecutionEventBindingName(), + new JobExecutionEvent(jobExecution)); } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingSkipListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingSkipListener.java index e05336e8..c1afcca3 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingSkipListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingSkipListener.java @@ -67,7 +67,8 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInRead: " + t.getMessage(), t); } - this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), "Skipped when reading.", t.getMessage()); + this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), + "Skipped when reading.", t.getMessage()); } @Override @@ -75,7 +76,8 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInWrite: " + t.getMessage(), t); } - this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), item, t.getMessage()); + this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), item, + t.getMessage()); } @Override @@ -83,7 +85,8 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInProcess: " + t.getMessage(), t); } - this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), item, t.getMessage()); + this.messagePublisher.publishWithThrowableHeader(this.properties.getSkipEventBindingName(), item, + t.getMessage()); } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingStepExecutionListener.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingStepExecutionListener.java index 40611534..8325bac7 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingStepExecutionListener.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/EventEmittingStepExecutionListener.java @@ -34,10 +34,10 @@ import org.springframework.util.Assert; * @author Glenn Renfro * @author Ali Shahbour */ -public class EventEmittingStepExecutionListener - implements StepExecutionListener, Ordered { +public class EventEmittingStepExecutionListener implements StepExecutionListener, Ordered { private final MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; private TaskEventProperties properties; @@ -50,19 +50,22 @@ public class EventEmittingStepExecutionListener this.properties = properties; } - public EventEmittingStepExecutionListener(MessagePublisher messagePublisher, int order, TaskEventProperties properties) { + public EventEmittingStepExecutionListener(MessagePublisher messagePublisher, int order, + TaskEventProperties properties) { this(messagePublisher, properties); this.order = order; } @Override public void beforeStep(StepExecution stepExecution) { - this.messagePublisher.publish(this.properties.getStepExecutionEventBindingName(), new StepExecutionEvent(stepExecution)); + this.messagePublisher.publish(this.properties.getStepExecutionEventBindingName(), + new StepExecutionEvent(stepExecution)); } @Override public ExitStatus afterStep(StepExecution stepExecution) { - this.messagePublisher.publish(this.properties.getStepExecutionEventBindingName(), new StepExecutionEvent(stepExecution)); + this.messagePublisher.publish(this.properties.getStepExecutionEventBindingName(), + new StepExecutionEvent(stepExecution)); return stepExecution.getExitStatus(); } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobExecutionEvent.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobExecutionEvent.java index b99599c0..43051c59 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobExecutionEvent.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobExecutionEvent.java @@ -57,8 +57,7 @@ public class JobExecutionEvent extends Entity { private Date lastUpdated = null; - private ExitStatus exitStatus = new ExitStatus( - new org.springframework.batch.core.ExitStatus("UNKNOWN")); + private ExitStatus exitStatus = new ExitStatus(new org.springframework.batch.core.ExitStatus("UNKNOWN")); private ExecutionContext executionContext = new ExecutionContext(); @@ -73,8 +72,7 @@ public class JobExecutionEvent extends Entity { * @param original the StepExecution to build this DTO around. */ public JobExecutionEvent(JobExecution original) { - this.jobParameters = new JobParametersEvent( - original.getJobParameters().getParameters()); + this.jobParameters = new JobParametersEvent(original.getJobParameters().getParameters()); this.jobInstance = new JobInstanceEvent(original.getJobInstance().getId(), original.getJobInstance().getJobName()); for (StepExecution stepExecution : original.getStepExecutions()) { @@ -264,8 +262,8 @@ public class JobExecutionEvent extends Entity { public String toString() { return super.toString() + String.format( ", startTime=%s, endTime=%s, lastUpdated=%s, status=%s, exitStatus=%s, job=[%s], jobParameters=[%s]", - this.startTime, this.endTime, this.lastUpdated, this.status, - this.exitStatus, this.jobInstance, this.jobParameters); + this.startTime, this.endTime, this.lastUpdated, this.status, this.exitStatus, this.jobInstance, + this.jobParameters); } } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParameterEvent.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParameterEvent.java index df428cdf..c9f8f988 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParameterEvent.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParameterEvent.java @@ -79,25 +79,22 @@ public class JobParameterEvent { } JobParameterEvent rhs = (JobParameterEvent) obj; - return this.parameter == null - ? rhs.parameter == null && this.parameterType == rhs.parameterType + return this.parameter == null ? rhs.parameter == null && this.parameterType == rhs.parameterType : this.parameter.equals(rhs.parameter); } @Override public String toString() { - return this.parameter == null ? null - : (this.parameterType == JobParameterEvent.ParameterType.DATE - ? "" + ((Date) this.parameter).getTime() - : this.parameter.toString()); + return this.parameter == null ? null : (this.parameterType == JobParameterEvent.ParameterType.DATE + ? "" + ((Date) this.parameter).getTime() : this.parameter.toString()); } @Override public int hashCode() { final int BASE_HASH = 7; final int MULTIPLIER_HASH = 21; - return BASE_HASH + MULTIPLIER_HASH * (this.parameter == null - ? this.parameterType.hashCode() : this.parameter.hashCode()); + return BASE_HASH + MULTIPLIER_HASH + * (this.parameter == null ? this.parameterType.hashCode() : this.parameter.hashCode()); } /** diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParametersEvent.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParametersEvent.java index ede37185..7fdf8044 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParametersEvent.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobParametersEvent.java @@ -42,20 +42,16 @@ public class JobParametersEvent { this.parameters = new LinkedHashMap<>(); for (Map.Entry entry : jobParameters.entrySet()) { if (entry.getValue().getValue() instanceof String) { - this.parameters.put(entry.getKey(), - new JobParameterEvent(entry.getValue())); + this.parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); } else if (entry.getValue().getValue() instanceof Long) { - this.parameters.put(entry.getKey(), - new JobParameterEvent(entry.getValue())); + this.parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); } else if (entry.getValue().getValue() instanceof Date) { - this.parameters.put(entry.getKey(), - new JobParameterEvent(entry.getValue())); + this.parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); } else if (entry.getValue().getValue() instanceof Double) { - this.parameters.put(entry.getKey(), - new JobParameterEvent(entry.getValue())); + this.parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); } } } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/MessagePublisher.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/MessagePublisher.java index d500f785..7d795fb0 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/MessagePublisher.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/MessagePublisher.java @@ -29,7 +29,6 @@ import org.springframework.util.Assert; */ public class MessagePublisher

{ - private final StreamBridge streamBridge; public MessagePublisher(StreamBridge streamBridge) { @@ -52,8 +51,8 @@ public class MessagePublisher

{ } public void publishWithThrowableHeader(String bindingName, P payload, String header) { - Message

message = MessageBuilder.withPayload(payload) - .setHeader(BatchJobHeaders.BATCH_EXCEPTION, header).build(); + Message

message = MessageBuilder.withPayload(payload).setHeader(BatchJobHeaders.BATCH_EXCEPTION, header) + .build(); publishMessage(bindingName, message); } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/StepExecutionEvent.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/StepExecutionEvent.java index e7d27d55..057c7f70 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/StepExecutionEvent.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/StepExecutionEvent.java @@ -63,8 +63,7 @@ public class StepExecutionEvent extends Entity { private ExecutionContext executionContext = new ExecutionContext(); - private ExitStatus exitStatus = new ExitStatus( - org.springframework.batch.core.ExitStatus.EXECUTING); + private ExitStatus exitStatus = new ExitStatus(org.springframework.batch.core.ExitStatus.EXECUTING); private boolean terminateOnly; @@ -82,8 +81,7 @@ public class StepExecutionEvent extends Entity { */ public StepExecutionEvent(StepExecution stepExecution) { super(); - Assert.notNull(stepExecution, - "StepExecution must be provided to re-hydrate an existing StepExecutionEvent"); + Assert.notNull(stepExecution, "StepExecution must be provided to re-hydrate an existing StepExecutionEvent"); Assert.notNull(stepExecution.getJobExecution(), "JobExecution must be provided to re-hydrate an existing StepExecutionEvent"); setId(stepExecution.getId()); @@ -393,8 +391,7 @@ public class StepExecutionEvent extends Entity { } StepExecution other = (StepExecution) obj; - return this.stepName.equals(other.getStepName()) - && (this.jobExecutionId == other.getJobExecutionId()) + return this.stepName.equals(other.getStepName()) && (this.jobExecutionId == other.getJobExecutionId()) && getId().equals(other.getId()); } @@ -407,16 +404,13 @@ public class StepExecutionEvent extends Entity { public int hashCode() { Object jobExecutionId = getJobExecutionId(); Long id = getId(); - return super.hashCode() - + 31 * (this.stepName != null ? this.stepName.hashCode() : 0) - + 91 * (jobExecutionId != null ? jobExecutionId.hashCode() : 0) - + 59 * (id != null ? id.hashCode() : 0); + return super.hashCode() + 31 * (this.stepName != null ? this.stepName.hashCode() : 0) + + 91 * (jobExecutionId != null ? jobExecutionId.hashCode() : 0) + 59 * (id != null ? id.hashCode() : 0); } @Override public String toString() { - return String.format(getSummary() + ", exitDescription=%s", - this.exitStatus.getExitDescription()); + return String.format(getSummary() + ", exitDescription=%s", this.exitStatus.getExitDescription()); } public String getSummary() { @@ -424,9 +418,8 @@ public class StepExecutionEvent extends Entity { ", name=%s, status=%s, exitStatus=%s, readCount=%d, " + "filterCount=%d, writeCount=%d readSkipCount=%d, writeSkipCount=%d" + ", processSkipCount=%d, commitCount=%d, rollbackCount=%d", - this.stepName, this.status, this.exitStatus.getExitCode(), this.readCount, - this.filterCount, this.writeCount, this.readSkipCount, - this.writeSkipCount, this.processSkipCount, this.commitCount, + this.stepName, this.status, this.exitStatus.getExitCode(), this.readCount, this.filterCount, + this.writeCount, this.readSkipCount, this.writeSkipCount, this.processSkipCount, this.commitCount, this.rollbackCount); } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskBatchEventListenerBeanPostProcessor.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskBatchEventListenerBeanPostProcessor.java index 4c588532..3f97c948 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskBatchEventListenerBeanPostProcessor.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskBatchEventListenerBeanPostProcessor.java @@ -70,8 +70,7 @@ public class TaskBatchEventListenerBeanPostProcessor implements BeanPostProcesso private ApplicationContext applicationContext; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { registerJobExecutionEventListener(bean); @@ -83,13 +82,11 @@ public class TaskBatchEventListenerBeanPostProcessor implements BeanPostProcesso registerChunkEventsListener(bean); if (tasklet instanceof ChunkOrientedTasklet) { - Field chunkProviderField = ReflectionUtils - .findField(ChunkOrientedTasklet.class, "chunkProvider"); + Field chunkProviderField = ReflectionUtils.findField(ChunkOrientedTasklet.class, "chunkProvider"); ReflectionUtils.makeAccessible(chunkProviderField); SimpleChunkProvider chunkProvider = (SimpleChunkProvider) ReflectionUtils .getField(chunkProviderField, tasklet); - Field chunkProcessorField = ReflectionUtils - .findField(ChunkOrientedTasklet.class, "chunkProcessor"); + Field chunkProcessorField = ReflectionUtils.findField(ChunkOrientedTasklet.class, "chunkProcessor"); ReflectionUtils.makeAccessible(chunkProcessorField); SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils .getField(chunkProcessorField, tasklet); @@ -106,63 +103,55 @@ public class TaskBatchEventListenerBeanPostProcessor implements BeanPostProcesso } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } private void registerItemProcessEvents(SimpleChunkProcessor chunkProcessor) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER)) { + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER)) { chunkProcessor.registerListener((ItemProcessListener) this.applicationContext .getBean(BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER)); } } private void registerItemReadEvents(SimpleChunkProvider chunkProvider) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER)) { + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER)) { chunkProvider.registerListener((ItemReadListener) this.applicationContext .getBean(BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER)); } } private void registerItemWriteEvents(SimpleChunkProcessor chunkProcessor) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER)) { + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER)) { chunkProcessor.registerListener((ItemWriteListener) this.applicationContext .getBean(BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER)); } } private void registerSkipEvents(SimpleChunkProvider chunkProvider) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)) { - chunkProvider.registerListener((SkipListener) this.applicationContext - .getBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)); + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)) { + chunkProvider.registerListener( + (SkipListener) this.applicationContext.getBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)); } } private void registerSkipEvents(SimpleChunkProcessor chunkProcessor) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)) { - chunkProcessor.registerListener((SkipListener) this.applicationContext - .getBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)); + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)) { + chunkProcessor.registerListener( + (SkipListener) this.applicationContext.getBean(BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER)); } } private void registerChunkEventsListener(Object bean) { - if (this.applicationContext - .containsBean(BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER)) { - ((TaskletStep) bean) - .registerChunkListener((ChunkListener) this.applicationContext - .getBean(BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER)); + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER)) { + ((TaskletStep) bean).registerChunkListener( + (ChunkListener) this.applicationContext.getBean(BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER)); } } private void registerJobExecutionEventListener(Object bean) { - if (bean instanceof AbstractJob && this.applicationContext.containsBean( - BatchEventAutoConfiguration.JOB_EXECUTION_EVENTS_LISTENER)) { + if (bean instanceof AbstractJob + && this.applicationContext.containsBean(BatchEventAutoConfiguration.JOB_EXECUTION_EVENTS_LISTENER)) { JobExecutionListener jobExecutionEventsListener = (JobExecutionListener) this.applicationContext .getBean(BatchEventAutoConfiguration.JOB_EXECUTION_EVENTS_LISTENER); @@ -172,8 +161,7 @@ public class TaskBatchEventListenerBeanPostProcessor implements BeanPostProcesso } private void registerStepExecutionEventListener(Object bean) { - if (this.applicationContext.containsBean( - BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER)) { + if (this.applicationContext.containsBean(BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER)) { StepExecutionListener stepExecutionListener = (StepExecutionListener) this.applicationContext .getBean(BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER); AbstractStep step = (AbstractStep) bean; diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskEventProperties.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskEventProperties.java index ea77d0ad..cace8cc0 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskEventProperties.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/TaskEventProperties.java @@ -68,12 +68,19 @@ public class TaskEventProperties { private int skipOrder = Ordered.LOWEST_PRECEDENCE; private String jobExecutionEventBindingName = "job-execution-events"; + private String skipEventBindingName = "skip-events"; + private String chunkEventBindingName = "chunk-events"; + private String itemProcessEventBindingName = "item-process-events"; + private String itemReadEventBindingName = "item-read-events"; + private String itemWriteEventBindingName = "item-write-events"; + private String stepExecutionEventBindingName = "step-execution-events"; + private String taskEventBindingName = "task-events"; public int getJobExecutionOrder() { @@ -132,7 +139,6 @@ public class TaskEventProperties { this.skipOrder = skipOrder; } - public String getJobExecutionEventBindingName() { return jobExecutionEventBindingName; } @@ -196,4 +202,5 @@ public class TaskEventProperties { public void setTaskEventBindingName(String taskEventBindingName) { this.taskEventBindingName = taskEventBindingName; } + } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLaunchRequest.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLaunchRequest.java index 6a247291..e3535c6e 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLaunchRequest.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLaunchRequest.java @@ -56,18 +56,14 @@ public class TaskLaunchRequest implements Serializable { * @param applicationName name to be applied to the launched task. If set to null then * the launched task name will be "Task-`hash code of the TaskLaunchRequest`. */ - public TaskLaunchRequest(String uri, List commandlineArguments, - Map environmentProperties, + public TaskLaunchRequest(String uri, List commandlineArguments, Map environmentProperties, Map deploymentProperties, String applicationName) { Assert.hasText(uri, "uri must not be empty nor null."); this.uri = uri; - this.commandlineArguments = (commandlineArguments == null) ? new ArrayList<>() - : commandlineArguments; - this.environmentProperties = environmentProperties == null ? new HashMap<>() - : environmentProperties; - this.deploymentProperties = deploymentProperties == null ? new HashMap<>() - : deploymentProperties; + this.commandlineArguments = (commandlineArguments == null) ? new ArrayList<>() : commandlineArguments; + this.environmentProperties = environmentProperties == null ? new HashMap<>() : environmentProperties; + this.deploymentProperties = deploymentProperties == null ? new HashMap<>() : deploymentProperties; setApplicationName(applicationName); } @@ -125,16 +121,15 @@ public class TaskLaunchRequest implements Serializable { * @param applicationName the name to be */ public void setApplicationName(String applicationName) { - this.applicationName = !StringUtils.hasText(applicationName) - ? "Task-" + UUID.randomUUID().toString() : applicationName; + this.applicationName = !StringUtils.hasText(applicationName) ? "Task-" + UUID.randomUUID().toString() + : applicationName; } @Override public String toString() { - return "TaskLaunchRequest{" + "uri='" + this.uri + '\'' - + ", commandlineArguments=" + this.commandlineArguments - + ", environmentProperties=" + this.environmentProperties - + ", deploymentProperties=" + this.deploymentProperties + '}'; + return "TaskLaunchRequest{" + "uri='" + this.uri + '\'' + ", commandlineArguments=" + this.commandlineArguments + + ", environmentProperties=" + this.environmentProperties + ", deploymentProperties=" + + this.deploymentProperties + '}'; } @Override diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLauncherSink.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLauncherSink.java index 82f46881..34981875 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLauncherSink.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/TaskLauncherSink.java @@ -65,12 +65,10 @@ public class TaskLauncherSink { Assert.notNull(this.taskLauncher, "TaskLauncher has not been initialized"); logger.info("Launching Task for the following uri " + taskLaunchRequest.getUri()); Resource resource = this.resourceLoader.getResource(taskLaunchRequest.getUri()); - AppDefinition definition = new AppDefinition( - taskLaunchRequest.getApplicationName(), + AppDefinition definition = new AppDefinition(taskLaunchRequest.getApplicationName(), taskLaunchRequest.getEnvironmentProperties()); AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, - taskLaunchRequest.getDeploymentProperties(), - taskLaunchRequest.getCommandlineArguments()); + taskLaunchRequest.getDeploymentProperties(), taskLaunchRequest.getCommandlineArguments()); this.taskLauncher.launch(request); } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/listener/TaskEventAutoConfiguration.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/listener/TaskEventAutoConfiguration.java index 7a61dad8..f22fee9f 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/listener/TaskEventAutoConfiguration.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/listener/TaskEventAutoConfiguration.java @@ -41,8 +41,8 @@ import org.springframework.context.annotation.PropertySource; @ConditionalOnBean(TaskLifecycleListener.class) @ConditionalOnExpression("T(org.springframework.util.StringUtils).isEmpty('${spring.batch.job.jobName:}')") // @checkstyle:off -@ConditionalOnProperty(prefix = "spring.cloud.task.events", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.cloud.task.events", name = "enabled", havingValue = "true", + matchIfMissing = true) // @checkstyle:on @PropertySource("classpath:/org/springframework/cloud/task/application.properties") @AutoConfigureBefore(BindingServiceConfiguration.class) @@ -55,8 +55,10 @@ public class TaskEventAutoConfiguration { */ @Configuration(proxyBeanMethods = false) public static class ListenerConfiguration { + @Bean - public TaskExecutionListener taskEventEmitter(StreamBridge streamBridge, TaskEventProperties taskEventProperties) { + public TaskExecutionListener taskEventEmitter(StreamBridge streamBridge, + TaskEventProperties taskEventProperties) { return new TaskExecutionListener() { @Override public void onTaskStartup(TaskExecution taskExecution) { diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/EventListenerTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/EventListenerTests.java index 40f264f8..2a2d3da1 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/EventListenerTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/EventListenerTests.java @@ -78,27 +78,24 @@ public class EventListenerTests { @BeforeEach public void beforeTests() { this.applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(BatchEventsApplication.class)).web(WebApplicationType.NONE).build() - .run(); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(BatchEventsApplication.class)) + .web(WebApplicationType.NONE).build().run(); StreamBridge streamBridge = this.applicationContext.getBean(StreamBridge.class); MessagePublisher messagePublisher = new MessagePublisher(streamBridge); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - this.eventEmittingSkipListener = new EventEmittingSkipListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingItemProcessListener = new EventEmittingItemProcessListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingItemReadListener = new EventEmittingItemReadListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingItemWriteListener = new EventEmittingItemWriteListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingJobExecutionListener = new EventEmittingJobExecutionListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingStepExecutionListener = new EventEmittingStepExecutionListener( - messagePublisher, this.taskEventProperties); - this.eventEmittingChunkListener = new EventEmittingChunkListener( - messagePublisher, 0, this.taskEventProperties); + this.eventEmittingSkipListener = new EventEmittingSkipListener(messagePublisher, this.taskEventProperties); + this.eventEmittingItemProcessListener = new EventEmittingItemProcessListener(messagePublisher, + this.taskEventProperties); + this.eventEmittingItemReadListener = new EventEmittingItemReadListener(messagePublisher, + this.taskEventProperties); + this.eventEmittingItemWriteListener = new EventEmittingItemWriteListener(messagePublisher, + this.taskEventProperties); + this.eventEmittingJobExecutionListener = new EventEmittingJobExecutionListener(messagePublisher, + this.taskEventProperties); + this.eventEmittingStepExecutionListener = new EventEmittingStepExecutionListener(messagePublisher, + this.taskEventProperties); + this.eventEmittingChunkListener = new EventEmittingChunkListener(messagePublisher, 0, this.taskEventProperties); } @AfterEach @@ -110,25 +107,18 @@ public class EventListenerTests { @Test public void testEventListenerOrderProperty() { - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingSkipListener.getOrder()); - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingItemProcessListener.getOrder()); - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingItemReadListener.getOrder()); - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingItemWriteListener.getOrder()); - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingJobExecutionListener.getOrder()); - assertThat(Ordered.LOWEST_PRECEDENCE) - .isEqualTo(this.eventEmittingStepExecutionListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingSkipListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingItemProcessListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingItemReadListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingItemWriteListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingJobExecutionListener.getOrder()); + assertThat(Ordered.LOWEST_PRECEDENCE).isEqualTo(this.eventEmittingStepExecutionListener.getOrder()); assertThat(0).isEqualTo(this.eventEmittingChunkListener.getOrder()); } @Test public void testItemProcessListenerOnProcessorError() { - this.eventEmittingItemProcessListener.onProcessError("HELLO", - new RuntimeException("Test Exception")); + this.eventEmittingItemProcessListener.onProcessError("HELLO", new RuntimeException("Test Exception")); assertThat(getStringFromDestination(this.taskEventProperties.getItemProcessEventBindingName())) .isEqualTo("Exception while item was being processed"); @@ -136,18 +126,17 @@ public class EventListenerTests { @Test public void testItemProcessListenerAfterProcess() { - this.eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS_EQUAL", - "HELLO_AFTER_PROCESS_EQUAL"); + this.eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS_EQUAL", "HELLO_AFTER_PROCESS_EQUAL"); assertThat(getStringFromDestination(this.taskEventProperties.getItemProcessEventBindingName())) - .isEqualTo("item equaled result after processing"); + .isEqualTo("item equaled result after processing"); this.eventEmittingItemProcessListener.afterProcess("HELLO_NOT_EQUAL", "WORLD"); assertThat(getStringFromDestination(this.taskEventProperties.getItemProcessEventBindingName())) .isEqualTo("item did not equal result after processing"); this.eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS", null); - assertThat(getStringFromDestination(this.taskEventProperties. - getItemProcessEventBindingName())).isEqualTo("1 item was filtered"); + assertThat(getStringFromDestination(this.taskEventProperties.getItemProcessEventBindingName())) + .isEqualTo("1 item was filtered"); } @Test @@ -159,33 +148,29 @@ public class EventListenerTests { @Test public void EventEmittingSkipListenerSkipRead() { this.eventEmittingSkipListener.onSkipInRead(new RuntimeException("Text Exception")); - assertThat(getStringFromDestination(this.taskEventProperties. - getSkipEventBindingName())).isEqualTo("Skipped when reading."); + assertThat(getStringFromDestination(this.taskEventProperties.getSkipEventBindingName())) + .isEqualTo("Skipped when reading."); } @Test public void EventEmittingSkipListenerSkipWrite() { final String MESSAGE = "\"HELLO_SKIP_WRITE\""; - this.eventEmittingSkipListener.onSkipInWrite(MESSAGE, - new RuntimeException("Text Exception")); - assertThat(getStringFromDestination(this.taskEventProperties. - getSkipEventBindingName())).isEqualTo(MESSAGE); + this.eventEmittingSkipListener.onSkipInWrite(MESSAGE, new RuntimeException("Text Exception")); + assertThat(getStringFromDestination(this.taskEventProperties.getSkipEventBindingName())).isEqualTo(MESSAGE); } @Test public void EventEmittingSkipListenerSkipProcess() { final String MESSAGE = "\"HELLO_SKIP_PROCESS\""; - this.eventEmittingSkipListener.onSkipInProcess(MESSAGE, - new RuntimeException("Text Exception")); - assertThat(getStringFromDestination(this.taskEventProperties. - getSkipEventBindingName())).isEqualTo(MESSAGE); + this.eventEmittingSkipListener.onSkipInProcess(MESSAGE, new RuntimeException("Text Exception")); + assertThat(getStringFromDestination(this.taskEventProperties.getSkipEventBindingName())).isEqualTo(MESSAGE); } @Test public void EventEmittingItemReadListener() { this.eventEmittingItemReadListener.onReadError(new RuntimeException("Text Exception")); - assertThat(getStringFromDestination(this.taskEventProperties. - getItemReadEventBindingName())).isEqualTo("Exception while item was being read"); + assertThat(getStringFromDestination(this.taskEventProperties.getItemReadEventBindingName())) + .isEqualTo("Exception while item was being read"); } @Test @@ -204,14 +189,14 @@ public class EventListenerTests { public void EventEmittingItemWriteListenerBeforeWrite() { this.eventEmittingItemWriteListener.beforeWrite(getSampleList()); assertThat(getStringFromDestination(this.taskEventProperties.getItemWriteEventBindingName())) - .isEqualTo("3 items to be written."); + .isEqualTo("3 items to be written."); } @Test public void EventEmittingItemWriteListenerAfterWrite() { this.eventEmittingItemWriteListener.afterWrite(getSampleList()); assertThat(getStringFromDestination(this.taskEventProperties.getItemWriteEventBindingName())) - .isEqualTo("3 items have been written."); + .isEqualTo("3 items have been written."); } @Test @@ -230,9 +215,8 @@ public class EventListenerTests { List> result = testListener(this.taskEventProperties.getJobExecutionEventBindingName(), 1); assertThat(result.get(0)).isNotNull(); - JobExecutionEvent jobEvent = this.objectMapper.readValue(result.get(0).getPayload(), JobExecutionEvent.class); - assertThat(jobEvent.getJobInstance().getJobName()) - .isEqualTo(jobExecution.getJobInstance().getJobName()); + JobExecutionEvent jobEvent = this.objectMapper.readValue(result.get(0).getPayload(), JobExecutionEvent.class); + assertThat(jobEvent.getJobInstance().getJobName()).isEqualTo(jobExecution.getJobInstance().getJobName()); } @Test @@ -242,9 +226,8 @@ public class EventListenerTests { List> result = testListener(this.taskEventProperties.getJobExecutionEventBindingName(), 1); assertThat(result.get(0)).isNotNull(); - JobExecutionEvent jobEvent = this.objectMapper.readValue(result.get(0).getPayload(), JobExecutionEvent.class); - assertThat(jobEvent.getJobInstance().getJobName()) - .isEqualTo(jobExecution.getJobInstance().getJobName()); + JobExecutionEvent jobEvent = this.objectMapper.readValue(result.get(0).getPayload(), JobExecutionEvent.class); + assertThat(jobEvent.getJobInstance().getJobName()).isEqualTo(jobExecution.getJobInstance().getJobName()); } @Test @@ -256,7 +239,8 @@ public class EventListenerTests { List> result = testListener(this.taskEventProperties.getStepExecutionEventBindingName(), 1); assertThat(result.get(0)).isNotNull(); - StepExecutionEvent stepExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), StepExecutionEvent.class); + StepExecutionEvent stepExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), + StepExecutionEvent.class); assertThat(stepExecutionEvent.getStepName()).isEqualTo(STEP_MESSAGE); } @@ -268,7 +252,8 @@ public class EventListenerTests { List> result = testListener(this.taskEventProperties.getStepExecutionEventBindingName(), 1); assertThat(result.get(0)).isNotNull(); - StepExecutionEvent stepExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), StepExecutionEvent.class); + StepExecutionEvent stepExecutionEvent = this.objectMapper.readValue(result.get(0).getPayload(), + StepExecutionEvent.class); assertThat(stepExecutionEvent.getStepName()).isEqualTo(STEP_MESSAGE); } @@ -277,7 +262,7 @@ public class EventListenerTests { final String CHUNK_MESSAGE = "Before Chunk Processing"; this.eventEmittingChunkListener.beforeChunk(getChunkContext()); assertThat(getStringFromDestination(this.taskEventProperties.getChunkEventBindingName())) - .isEqualTo(CHUNK_MESSAGE); + .isEqualTo(CHUNK_MESSAGE); } @Test @@ -285,7 +270,7 @@ public class EventListenerTests { final String CHUNK_MESSAGE = "After Chunk Processing"; this.eventEmittingChunkListener.afterChunk(getChunkContext()); assertThat(getStringFromDestination(this.taskEventProperties.getChunkEventBindingName())) - .isEqualTo(CHUNK_MESSAGE); + .isEqualTo(CHUNK_MESSAGE); } @Test @@ -340,5 +325,7 @@ public class EventListenerTests { @SpringBootApplication public static class BatchEventsApplication { + } + } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobExecutionEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobExecutionEventTests.java index 35be8096..86712451 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobExecutionEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobExecutionEventTests.java @@ -60,14 +60,12 @@ public class JobExecutionEventTests { private static final Long JOB_EXECUTION_ID = 2L; - private static final String[] LISTENER_BEAN_NAMES = { - BatchEventAutoConfiguration.JOB_EXECUTION_EVENTS_LISTENER, - BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER, - BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER, - BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER, - BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER, - BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER, - BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER}; + private static final String[] LISTENER_BEAN_NAMES = { BatchEventAutoConfiguration.JOB_EXECUTION_EVENTS_LISTENER, + BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER, + BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER, BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER, + BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER, + BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER, + BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER }; private JobParameters jobParameters; @@ -83,31 +81,26 @@ public class JobExecutionEventTests { @Test public void testBasic() { JobExecution jobExecution; - jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, - this.jobParameters); + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, this.jobParameters); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(jobExecution); - assertThat(jobExecutionEvent.getJobInstance()) - .as("jobInstance should not be null").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters()) - .as("jobParameters should not be null").isNotNull(); + assertThat(jobExecutionEvent.getJobInstance()).as("jobInstance should not be null").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters()).as("jobParameters should not be null").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters().getParameters().size()) - .as("jobParameters size did not match").isEqualTo(0); - assertThat(jobExecutionEvent.getJobInstance().getJobName()) - .as("jobInstance name did not match").isEqualTo(JOB_NAME); - assertThat(jobExecutionEvent.getStepExecutions().size()) - .as("no step executions were expected").isEqualTo(0); - assertThat(jobExecutionEvent.getExitStatus().getExitCode()) - .as("exitStatus did not match expected").isEqualTo("UNKNOWN"); + assertThat(jobExecutionEvent.getJobParameters().getParameters().size()).as("jobParameters size did not match") + .isEqualTo(0); + assertThat(jobExecutionEvent.getJobInstance().getJobName()).as("jobInstance name did not match") + .isEqualTo(JOB_NAME); + assertThat(jobExecutionEvent.getStepExecutions().size()).as("no step executions were expected").isEqualTo(0); + assertThat(jobExecutionEvent.getExitStatus().getExitCode()).as("exitStatus did not match expected") + .isEqualTo("UNKNOWN"); } @Test public void testJobParameters() { - String[] JOB_PARAM_KEYS = {"A", "B", "C", "D"}; + String[] JOB_PARAM_KEYS = { "A", "B", "C", "D" }; Date testDate = new Date(); - JobParameter[] PARAMETERS = {new JobParameter("FOO", true), - new JobParameter(1L, true), new JobParameter(1D, true), - new JobParameter(testDate, false)}; + JobParameter[] PARAMETERS = { new JobParameter("FOO", true), new JobParameter(1L, true), + new JobParameter(1D, true), new JobParameter(testDate, false) }; Map jobParamMap = new LinkedHashMap<>(); for (int paramCount = 0; paramCount < JOB_PARAM_KEYS.length; paramCount++) { @@ -115,34 +108,28 @@ public class JobExecutionEventTests { } this.jobParameters = new JobParameters(jobParamMap); JobExecution jobExecution; - jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, - this.jobParameters); + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, this.jobParameters); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(jobExecution); - assertThat(jobExecutionEvent.getJobParameters().getString("A")) - .as("Job Parameter A was expected").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters().getLong("B")) - .as("Job Parameter B was expected").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters().getDouble("C")) - .as("Job Parameter C was expected").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters().getDate("D")) - .as("Job Parameter D was expected").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters().getString("A")).as("Job Parameter A was expected").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters().getLong("B")).as("Job Parameter B was expected").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters().getDouble("C")).as("Job Parameter C was expected").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters().getDate("D")).as("Job Parameter D was expected").isNotNull(); - assertThat(jobExecutionEvent.getJobParameters().getString("A")) - .as("Job Parameter A value was not correct").isEqualTo("FOO"); - assertThat(jobExecutionEvent.getJobParameters().getLong("B")) - .as("Job Parameter B value was not correct").isEqualTo(Long.valueOf(1)); - assertThat(jobExecutionEvent.getJobParameters().getDouble("C")) - .as("Job Parameter C value was not correct").isEqualTo(Double.valueOf(1)); - assertThat(jobExecutionEvent.getJobParameters().getDate("D")) - .as("Job Parameter D value was not correct").isEqualTo(testDate); + assertThat(jobExecutionEvent.getJobParameters().getString("A")).as("Job Parameter A value was not correct") + .isEqualTo("FOO"); + assertThat(jobExecutionEvent.getJobParameters().getLong("B")).as("Job Parameter B value was not correct") + .isEqualTo(Long.valueOf(1)); + assertThat(jobExecutionEvent.getJobParameters().getDouble("C")).as("Job Parameter C value was not correct") + .isEqualTo(Double.valueOf(1)); + assertThat(jobExecutionEvent.getJobParameters().getDate("D")).as("Job Parameter D value was not correct") + .isEqualTo(testDate); } @Test public void testStepExecutions() { JobExecution jobExecution; - jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, - this.jobParameters); + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, this.jobParameters); List stepsExecutions = new ArrayList<>(); stepsExecutions.add(new StepExecution("foo", jobExecution)); stepsExecutions.add(new StepExecution("bar", jobExecution)); @@ -150,16 +137,11 @@ public class JobExecutionEventTests { jobExecution.addStepExecutions(stepsExecutions); JobExecutionEvent jobExecutionsEvent = new JobExecutionEvent(jobExecution); - assertThat(jobExecutionsEvent.getStepExecutions().size()) - .as("stepExecutions count is incorrect").isEqualTo(3); - Iterator iter = jobExecutionsEvent.getStepExecutions() - .iterator(); - assertThat(iter.next().getStepName()).as("foo stepExecution is not present") - .isEqualTo("foo"); - assertThat(iter.next().getStepName()).as("bar stepExecution is not present") - .isEqualTo("bar"); - assertThat(iter.next().getStepName()).as("baz stepExecution is not present") - .isEqualTo("baz"); + assertThat(jobExecutionsEvent.getStepExecutions().size()).as("stepExecutions count is incorrect").isEqualTo(3); + Iterator iter = jobExecutionsEvent.getStepExecutions().iterator(); + assertThat(iter.next().getStepName()).as("foo stepExecution is not present").isEqualTo("foo"); + assertThat(iter.next().getStepName()).as("bar stepExecution is not present").isEqualTo("bar"); + assertThat(iter.next().getStepName()).as("baz stepExecution is not present").isEqualTo("baz"); } @Test @@ -167,7 +149,6 @@ public class JobExecutionEventTests { testDisabledConfiguration(null, null); } - @Test public void testDisabledJobExecutionListener() { testDisabledConfiguration("spring.cloud.task.batch.events.job-execution.enabled", @@ -177,10 +158,9 @@ public class JobExecutionEventTests { @Test public void testDisabledStepExecutionListener() { testDisabledConfiguration("spring.cloud.task.batch.events.step-execution.enabled", - BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER); + BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER); } - @Test public void testDisabledChunkListener() { testDisabledConfiguration("spring.cloud.task.batch.events.chunk.enabled", @@ -222,21 +202,17 @@ public class JobExecutionEventTests { final String EXCEPTION_MESSAGE = "TEST EXCEPTION"; JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); assertThat(jobExecutionEvent.getFailureExceptions().size()).isEqualTo(0); - jobExecutionEvent - .addFailureException(new IllegalStateException(EXCEPTION_MESSAGE)); + jobExecutionEvent.addFailureException(new IllegalStateException(EXCEPTION_MESSAGE)); assertThat(jobExecutionEvent.getFailureExceptions().size()).isEqualTo(1); assertThat(jobExecutionEvent.getAllFailureExceptions().size()).isEqualTo(1); - assertThat(EXCEPTION_MESSAGE) - .isEqualTo(jobExecutionEvent.getFailureExceptions().get(0).getMessage()); - assertThat(EXCEPTION_MESSAGE).isEqualTo( - jobExecutionEvent.getAllFailureExceptions().get(0).getMessage()); + assertThat(EXCEPTION_MESSAGE).isEqualTo(jobExecutionEvent.getFailureExceptions().get(0).getMessage()); + assertThat(EXCEPTION_MESSAGE).isEqualTo(jobExecutionEvent.getAllFailureExceptions().get(0).getMessage()); } @Test public void testToString() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertThat(jobExecutionEvent.toString().startsWith("JobExecutionEvent:")) - .isTrue(); + assertThat(jobExecutionEvent.toString().startsWith("JobExecutionEvent:")).isTrue(); } @Test @@ -273,10 +249,8 @@ public class JobExecutionEventTests { assertThat(jobExecutionEvent.getJobId()).isNull(); JobInstanceEvent expectedJobInstanceEvent = new JobInstanceEvent(1L, JOB_NAME); jobExecutionEvent.setJobInstance(expectedJobInstanceEvent); - assertThat(jobExecutionEvent.getJobInstance().getJobName()) - .isEqualTo(expectedJobInstanceEvent.getJobName()); - assertThat(jobExecutionEvent.getJobId()) - .isEqualTo(expectedJobInstanceEvent.getId()); + assertThat(jobExecutionEvent.getJobInstance().getJobName()).isEqualTo(expectedJobInstanceEvent.getJobName()); + assertThat(jobExecutionEvent.getJobId()).isEqualTo(expectedJobInstanceEvent.getId()); } @Test @@ -286,8 +260,7 @@ public class JobExecutionEventTests { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); assertThat(jobExecutionEvent.getExecutionContext()).isNotNull(); jobExecutionEvent.setExecutionContext(executionContext); - assertThat(jobExecutionEvent.getExecutionContext().getString("hello")) - .isEqualTo("world"); + assertThat(jobExecutionEvent.getExecutionContext().getString("hello")).isEqualTo("world"); } @Test @@ -311,15 +284,12 @@ public class JobExecutionEventTests { @Test public void testOrderConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) - .withUserConfiguration( - BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, - BatchEventTestApplication.class) + .withUserConfiguration(BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, + BatchEventTestApplication.class) .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", - "--spring.main.web-environment=false", - "--spring.cloud.task.batch.events.chunk-order=5", + "--spring.main.web-environment=false", "--spring.cloud.task.batch.events.chunk-order=5", "--spring.cloud.task.batch.events.item-process-order=5", "--spring.cloud.task.batch.events.item-read-order=5", "--spring.cloud.task.batch.events.item-write-order=5", @@ -329,8 +299,7 @@ public class JobExecutionEventTests { applicationContextRunner.run((context) -> { for (String beanName : LISTENER_BEAN_NAMES) { Ordered ordered = (Ordered) context.getBean(beanName); - assertThat(5).as("Expected order value of 5 for " + beanName) - .isEqualTo(ordered.getOrder()); + assertThat(5).as("Expected order value of 5 for " + beanName).isEqualTo(ordered.getOrder()); } }); @@ -339,34 +308,31 @@ public class JobExecutionEventTests { @Test public void singleStepBatchJobSkip() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) - .withUserConfiguration( - BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, - BatchEventTestApplication.class) - .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", - "--spring.main.web-environment=false", "spring.batch.job.jobName=FOO"); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) + .withUserConfiguration(BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, + BatchEventTestApplication.class) + .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", + "--spring.main.web-environment=false", "spring.batch.job.jobName=FOO"); applicationContextRunner.run((context) -> { - NoSuchBeanDefinitionException exception = Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> { - context.getBean("jobExecutionEventsListener"); - }); - assertThat(exception.getMessage()).contains( - String.format("No bean named 'jobExecutionEventsListener' available")); + NoSuchBeanDefinitionException exception = Assertions.assertThrows(NoSuchBeanDefinitionException.class, + () -> { + context.getBean("jobExecutionEventsListener"); + }); + assertThat(exception.getMessage()) + .contains(String.format("No bean named 'jobExecutionEventsListener' available")); }); } private void testDisabledConfiguration(String property, String disabledListener) { String disabledPropertyArg = (property != null) ? "--" + property + "=false" : ""; ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) - .withUserConfiguration( - BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, - BatchEventTestApplication.class) - .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", - "--spring.main.web-environment=false", disabledPropertyArg); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) + .withUserConfiguration(BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class, + BatchEventTestApplication.class) + .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", + "--spring.main.web-environment=false", disabledPropertyArg); applicationContextRunner.run((context) -> { boolean exceptionThrown = false; for (String beanName : LISTENER_BEAN_NAMES) { @@ -377,9 +343,8 @@ public class JobExecutionEventTests { catch (NoSuchBeanDefinitionException nsbde) { exceptionThrown = true; } - assertThat(exceptionThrown).as( - String.format("Did not expect %s bean in context", beanName)) - .isTrue(); + assertThat(exceptionThrown).as(String.format("Did not expect %s bean in context", beanName)) + .isTrue(); } else { context.getBean(beanName); @@ -390,5 +355,7 @@ public class JobExecutionEventTests { @SpringBootApplication public static class BatchEventTestApplication { + } + } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobInstanceEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobInstanceEventTests.java index c5642792..d80b04ba 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobInstanceEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobInstanceEventTests.java @@ -53,8 +53,7 @@ public class JobInstanceEventTests { @Test public void testToString() { JobInstanceEvent jobInstanceEvent = new JobInstanceEvent(INSTANCE_ID, JOB_NAME); - assertThat(jobInstanceEvent.toString()) - .isEqualTo("JobInstanceEvent: id=1, version=null, Job=[FOOBAR]"); + assertThat(jobInstanceEvent.toString()).isEqualTo("JobInstanceEvent: id=1, version=null, Job=[FOOBAR]"); } } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParameterEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParameterEventTests.java index 2e3797fb..d46da8a4 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParameterEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParameterEventTests.java @@ -46,15 +46,13 @@ public class JobParameterEventTests { JobParameter jobParameter = new JobParameter(EXPECTED_VALUE, true); JobParameterEvent jobParameterEvent = new JobParameterEvent(jobParameter); assertThat(jobParameterEvent.getValue()).isEqualTo(EXPECTED_VALUE); - assertThat(jobParameterEvent.getType()) - .isEqualTo(JobParameterEvent.ParameterType.STRING); + assertThat(jobParameterEvent.getType()).isEqualTo(JobParameterEvent.ParameterType.STRING); assertThat(jobParameterEvent.isIdentifying()).isTrue(); jobParameter = new JobParameter(EXPECTED_DATE_VALUE, true); jobParameterEvent = new JobParameterEvent(jobParameter); assertThat(jobParameterEvent.getValue()).isEqualTo(EXPECTED_DATE_VALUE); - assertThat(jobParameterEvent.getType()) - .isEqualTo(JobParameterEvent.ParameterType.DATE); + assertThat(jobParameterEvent.getType()).isEqualTo(JobParameterEvent.ParameterType.DATE); assertThat(jobParameterEvent.isIdentifying()).isTrue(); assertThat(new JobParameterEvent(jobParameter).equals(jobParameterEvent)).isTrue(); } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParametersEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParametersEventTests.java index 5ab23582..2f786f06 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParametersEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/JobParametersEventTests.java @@ -59,12 +59,10 @@ public class JobParametersEventTests { @Test public void testConstructor() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); - assertThat(jobParametersEvent.getString(STRING_KEY)) - .isEqualTo(STRING_PARAM.getValue()); + assertThat(jobParametersEvent.getString(STRING_KEY)).isEqualTo(STRING_PARAM.getValue()); assertThat(jobParametersEvent.getLong(LONG_KEY)).isEqualTo(LONG_PARAM.getValue()); assertThat(jobParametersEvent.getDate(DATE_KEY)).isEqualTo(DATE_PARAM.getValue()); - assertThat(jobParametersEvent.getDouble(DOUBLE_KEY)) - .isEqualTo(DOUBLE_PARAM.getValue()); + assertThat(jobParametersEvent.getDouble(DOUBLE_KEY)).isEqualTo(DOUBLE_PARAM.getValue()); JobParametersEvent jobParametersEventNew = getPopulatedParametersEvent(); assertThat(jobParametersEvent).isEqualTo(jobParametersEventNew); @@ -84,22 +82,17 @@ public class JobParametersEventTests { assertThat(jobParametersEvent.hashCode()).isNotNull(); JobParametersEvent jobParametersEventPopulated = getPopulatedParametersEvent(); assertThat(jobParametersEvent).isNotNull(); - assertThat(jobParametersEventPopulated.hashCode()) - .isNotEqualTo(jobParametersEvent.hashCode()); + assertThat(jobParametersEventPopulated.hashCode()).isNotEqualTo(jobParametersEvent.hashCode()); } @Test public void testToProperties() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); Properties properties = jobParametersEvent.toProperties(); - assertThat(jobParametersEvent.getString(DATE_KEY)) - .isEqualTo(properties.getProperty(DATE_KEY)); - assertThat(jobParametersEvent.getString(STRING_KEY)) - .isEqualTo(properties.getProperty(STRING_KEY)); - assertThat(jobParametersEvent.getString(LONG_KEY)) - .isEqualTo(properties.getProperty(LONG_KEY)); - assertThat(jobParametersEvent.getString(DOUBLE_KEY)) - .isEqualTo(properties.getProperty(DOUBLE_KEY)); + assertThat(jobParametersEvent.getString(DATE_KEY)).isEqualTo(properties.getProperty(DATE_KEY)); + assertThat(jobParametersEvent.getString(STRING_KEY)).isEqualTo(properties.getProperty(STRING_KEY)); + assertThat(jobParametersEvent.getString(LONG_KEY)).isEqualTo(properties.getProperty(LONG_KEY)); + assertThat(jobParametersEvent.getString(DOUBLE_KEY)).isEqualTo(properties.getProperty(DOUBLE_KEY)); } @Test @@ -114,20 +107,15 @@ public class JobParametersEventTests { assertThat(jobParametersEvent.getDouble("FOOBAR")).isEqualTo(Double.valueOf(0)); assertThat(jobParametersEvent.getLong("FOOBAR")).isEqualTo(Long.valueOf(0)); assertThat(jobParametersEvent.getDouble("FOOBAR", 5)).isEqualTo(Double.valueOf(5)); - assertThat(jobParametersEvent.getDouble(DOUBLE_KEY, 0)) - .isEqualTo(DOUBLE_PARAM.getValue()); + assertThat(jobParametersEvent.getDouble(DOUBLE_KEY, 0)).isEqualTo(DOUBLE_PARAM.getValue()); assertThat(jobParametersEvent.getLong("FOOBAR", 5)).isEqualTo(Long.valueOf(5)); - assertThat(jobParametersEvent.getLong(LONG_KEY, 5)) - .isEqualTo(LONG_PARAM.getValue()); - assertThat(jobParametersEvent.getString("FOOBAR", "TESTVAL")) - .isEqualTo("TESTVAL"); - assertThat(jobParametersEvent.getString(STRING_KEY, "TESTVAL")) - .isEqualTo(STRING_PARAM.getValue()); + assertThat(jobParametersEvent.getLong(LONG_KEY, 5)).isEqualTo(LONG_PARAM.getValue()); + assertThat(jobParametersEvent.getString("FOOBAR", "TESTVAL")).isEqualTo("TESTVAL"); + assertThat(jobParametersEvent.getString(STRING_KEY, "TESTVAL")).isEqualTo(STRING_PARAM.getValue()); Date date = new Date(); assertThat(jobParametersEvent.getDate("FOOBAR", date)).isEqualTo(date); - assertThat(jobParametersEvent.getDate(DATE_KEY, date)) - .isEqualTo(DATE_PARAM.getValue()); + assertThat(jobParametersEvent.getDate(DATE_KEY, date)).isEqualTo(DATE_PARAM.getValue()); } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/StepExecutionEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/StepExecutionEventTests.java index 94cceaab..2edadb91 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/StepExecutionEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/StepExecutionEventTests.java @@ -54,34 +54,24 @@ public class StepExecutionEventTests { stepExecution.setWriteSkipCount(5); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertThat(stepExecutionEvent.getStepName()) - .as("stepName result was not as expected").isEqualTo(STEP_NAME); - assertThat(stepExecutionEvent.getStartTime()) - .as("startTime result was not as expected") + assertThat(stepExecutionEvent.getStepName()).as("stepName result was not as expected").isEqualTo(STEP_NAME); + assertThat(stepExecutionEvent.getStartTime()).as("startTime result was not as expected") .isEqualTo(stepExecution.getStartTime()); - assertThat(stepExecutionEvent.getEndTime()) - .as("endTime result was not as expected") + assertThat(stepExecutionEvent.getEndTime()).as("endTime result was not as expected") .isEqualTo(stepExecution.getEndTime()); - assertThat(stepExecutionEvent.getLastUpdated()) - .as("lastUpdated result was not as expected") + assertThat(stepExecutionEvent.getLastUpdated()).as("lastUpdated result was not as expected") .isEqualTo(stepExecution.getLastUpdated()); - assertThat(stepExecutionEvent.getCommitCount()) - .as("commitCount result was not as expected") + assertThat(stepExecutionEvent.getCommitCount()).as("commitCount result was not as expected") .isEqualTo(stepExecution.getCommitCount()); - assertThat(stepExecutionEvent.getReadCount()) - .as("readCount result was not as expected") + assertThat(stepExecutionEvent.getReadCount()).as("readCount result was not as expected") .isEqualTo(stepExecution.getReadCount()); - assertThat(stepExecutionEvent.getReadSkipCount()) - .as("readSkipCount result was not as expected") + assertThat(stepExecutionEvent.getReadSkipCount()).as("readSkipCount result was not as expected") .isEqualTo(stepExecution.getReadSkipCount()); - assertThat(stepExecutionEvent.getWriteCount()) - .as("writeCount result was not as expected") + assertThat(stepExecutionEvent.getWriteCount()).as("writeCount result was not as expected") .isEqualTo(stepExecution.getWriteCount()); - assertThat(stepExecutionEvent.getWriteSkipCount()) - .as("writeSkipCount result was not as expected") + assertThat(stepExecutionEvent.getWriteSkipCount()).as("writeSkipCount result was not as expected") .isEqualTo(stepExecution.getWriteSkipCount()); - assertThat(stepExecutionEvent.getSkipCount()) - .as("skipCount result was not as expected") + assertThat(stepExecutionEvent.getSkipCount()).as("skipCount result was not as expected") .isEqualTo(stepExecution.getSkipCount()); } @@ -99,8 +89,8 @@ public class StepExecutionEventTests { public void testGetSummary() { StepExecution stepExecution = getBasicStepExecution(); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertThat(stepExecutionEvent.getSummary()).isEqualTo( - "StepExecutionEvent: id=null, version=null, name=STEP_NAME, status=STARTING," + assertThat(stepExecutionEvent.getSummary()) + .isEqualTo("StepExecutionEvent: id=null, version=null, name=STEP_NAME, status=STARTING," + " exitStatus=EXECUTING, readCount=0, filterCount=0, writeCount=0 readSkipCount=0," + " writeSkipCount=0, processSkipCount=0, commitCount=0, rollbackCount=0"); } @@ -109,12 +99,10 @@ public class StepExecutionEventTests { public void testHashCode() { StepExecution stepExecution = getBasicStepExecution(); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertThat(stepExecutionEvent.toString()) - .isEqualTo("StepExecutionEvent: id=null, version=null, " - + "name=STEP_NAME, status=STARTING, exitStatus=EXECUTING, " - + "readCount=0, filterCount=0, writeCount=0 readSkipCount=0, " - + "writeSkipCount=0, processSkipCount=0, commitCount=0, " - + "rollbackCount=0, exitDescription="); + assertThat(stepExecutionEvent.toString()).isEqualTo("StepExecutionEvent: id=null, version=null, " + + "name=STEP_NAME, status=STARTING, exitStatus=EXECUTING, " + + "readCount=0, filterCount=0, writeCount=0 readSkipCount=0, " + + "writeSkipCount=0, processSkipCount=0, commitCount=0, " + "rollbackCount=0, exitDescription="); } @Test @@ -135,8 +123,7 @@ public class StepExecutionEventTests { @Test public void testSettersGetters() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( - getBasicStepExecution()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); Date date = new Date(); stepExecutionEvent.setLastUpdated(date); assertThat(stepExecutionEvent.getLastUpdated()).isEqualTo(date); @@ -186,8 +173,7 @@ public class StepExecutionEventTests { @Test public void testExitStatus() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( - getBasicStepExecution()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); final String EXIT_CODE = "1"; final String EXIT_DESCRIPTION = "EXPECTED FAILURE"; ExitStatus exitStatus = new ExitStatus(); @@ -198,14 +184,12 @@ public class StepExecutionEventTests { ExitStatus actualExitStatus = stepExecutionEvent.getExitStatus(); assertThat(actualExitStatus).isNotNull(); assertThat(actualExitStatus.getExitCode()).isEqualTo(exitStatus.getExitCode()); - assertThat(actualExitStatus.getExitDescription()) - .isEqualTo(exitStatus.getExitDescription()); + assertThat(actualExitStatus.getExitDescription()).isEqualTo(exitStatus.getExitDescription()); } @Test public void testBatchStatus() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( - getBasicStepExecution()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); stepExecutionEvent.setStatus(BatchStatus.ABANDONED); assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.ABANDONED); @@ -216,27 +200,23 @@ public class StepExecutionEventTests { StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(); assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); assertThat(stepExecutionEvent.getExitStatus()).isNotNull(); - assertThat(stepExecutionEvent.getExitStatus().getExitCode()) - .isEqualTo("EXECUTING"); + assertThat(stepExecutionEvent.getExitStatus().getExitCode()).isEqualTo("EXECUTING"); } @Test public void testExecutionContext() { ExecutionContext executionContext = new ExecutionContext(); executionContext.put("hello", "world"); - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( - getBasicStepExecution()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); assertThat(stepExecutionEvent.getExecutionContext()).isNotNull(); stepExecutionEvent.setExecutionContext(executionContext); - assertThat(stepExecutionEvent.getExecutionContext().getString("hello")) - .isEqualTo("world"); + assertThat(stepExecutionEvent.getExecutionContext().getString("hello")).isEqualTo("world"); } private StepExecution getBasicStepExecution() { JobInstance jobInstance = new JobInstance(JOB_INSTANCE_ID, JOB_NAME); JobParameters jobParameters = new JobParameters(); - JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, - jobParameters); + JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, jobParameters); return new StepExecution(STEP_NAME, jobExecution); } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchEventListenerBeanPostProcessorTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchEventListenerBeanPostProcessorTests.java index bec41a18..2b9b1462 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchEventListenerBeanPostProcessorTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchEventListenerBeanPostProcessorTests.java @@ -82,22 +82,16 @@ public class TaskBatchEventListenerBeanPostProcessorTests { @BeforeEach public void setupMock() { - when(this.taskletStep.getTasklet()).thenReturn( - new ChunkOrientedTasklet(this.chunkProvider, this.chunkProcessor)); + when(this.taskletStep.getTasklet()) + .thenReturn(new ChunkOrientedTasklet(this.chunkProvider, this.chunkProcessor)); when(this.taskletStep.getName()).thenReturn("FOOOBAR"); - registerAlias(ItemProcessListener.class, - BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER); - registerAlias(StepExecutionListener.class, - BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER); - registerAlias(ChunkListener.class, - BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER); - registerAlias(ItemReadListener.class, - BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER); - registerAlias(ItemWriteListener.class, - BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER); - registerAlias(SkipListener.class, - BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER); + registerAlias(ItemProcessListener.class, BatchEventAutoConfiguration.ITEM_PROCESS_EVENTS_LISTENER); + registerAlias(StepExecutionListener.class, BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER); + registerAlias(ChunkListener.class, BatchEventAutoConfiguration.CHUNK_EVENTS_LISTENER); + registerAlias(ItemReadListener.class, BatchEventAutoConfiguration.ITEM_READ_EVENTS_LISTENER); + registerAlias(ItemWriteListener.class, BatchEventAutoConfiguration.ITEM_WRITE_EVENTS_LISTENER); + registerAlias(SkipListener.class, BatchEventAutoConfiguration.SKIP_EVENTS_LISTENER); } @Test @@ -105,8 +99,8 @@ public class TaskBatchEventListenerBeanPostProcessorTests { TaskBatchEventListenerBeanPostProcessor postProcessor = this.context .getBean(TaskBatchEventListenerBeanPostProcessor.class); assertThat(postProcessor).isNotNull(); - TaskletStep updatedTaskletStep = (TaskletStep) postProcessor - .postProcessBeforeInitialization(this.taskletStep, "FOO"); + TaskletStep updatedTaskletStep = (TaskletStep) postProcessor.postProcessBeforeInitialization(this.taskletStep, + "FOO"); assertThat(updatedTaskletStep).isEqualTo(this.taskletStep); } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchConfigurationExistingTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchConfigurationExistingTests.java index 210d709b..a7b0aff1 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchConfigurationExistingTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchConfigurationExistingTests.java @@ -43,8 +43,8 @@ public class TaskLaunchConfigurationExistingTests { @Test public void testTaskLauncher() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TaskLaunchConfigurationExistingTests.TestTaskDeployerConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { + TaskLaunchConfigurationExistingTests.TestTaskDeployerConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.jmx.enabled=false")) { LocalTaskLauncher taskLauncher = context.getBean(LocalTaskLauncher.class); assertThat(testTaskLauncher).isNotNull(); assertThat(taskLauncher).isNotNull(); diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchRequestTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchRequestTests.java index c9897ea5..d483cff4 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchRequestTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLaunchRequestTests.java @@ -42,32 +42,28 @@ public class TaskLaunchRequestTests { args.add("foo"); map.put("bar", "baz"); - TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, - Collections.EMPTY_MAP, Collections.EMPTY_MAP, null); - TaskLaunchRequest request2 = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, - Collections.EMPTY_MAP, Collections.EMPTY_MAP, null); + TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, + Collections.EMPTY_MAP, null); + TaskLaunchRequest request2 = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, + Collections.EMPTY_MAP, null); assertThat(request.equals(null)).isFalse(); assertThat(request.equals("nope")).isFalse(); assertThat(request.equals(request)).isTrue(); assertThat(request.equals(request2)).isTrue(); - TaskLaunchRequest requestDiff = new TaskLaunchRequest("https://oops", - Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP, - null); + TaskLaunchRequest requestDiff = new TaskLaunchRequest("https://oops", Collections.EMPTY_LIST, + Collections.EMPTY_MAP, Collections.EMPTY_MAP, null); assertThat(request.equals(requestDiff)).isFalse(); - requestDiff = new TaskLaunchRequest(URI, args, Collections.EMPTY_MAP, - Collections.EMPTY_MAP, null); + requestDiff = new TaskLaunchRequest(URI, args, Collections.EMPTY_MAP, Collections.EMPTY_MAP, null); assertThat(request.equals(requestDiff)).isFalse(); requestDiff = new TaskLaunchRequest(URI, null, null, null, null); assertThat(request.equals(requestDiff)).isTrue(); - requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, map, - Collections.EMPTY_MAP, null); + requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, map, Collections.EMPTY_MAP, null); assertThat(request.equals(requestDiff)).isFalse(); - requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, - Collections.EMPTY_MAP, map, null); + requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, map, null); assertThat(request.equals(requestDiff)).isFalse(); assertThat(request.hashCode()).isEqualTo(request.hashCode()); @@ -76,12 +72,12 @@ public class TaskLaunchRequestTests { @Test public void testApplicationName() { - TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, - Collections.EMPTY_MAP, Collections.EMPTY_MAP, null); + TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, + Collections.EMPTY_MAP, null); assertThat(request.getApplicationName().startsWith("Task-")).isTrue(); - request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, - Collections.EMPTY_MAP, Collections.EMPTY_MAP, APP_NAME); + request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP, + APP_NAME); assertThat(request.getApplicationName()).isEqualTo(APP_NAME); } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherFunctionTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherFunctionTests.java index 8575ed94..908d0da9 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherFunctionTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherFunctionTests.java @@ -48,10 +48,9 @@ public class TaskLauncherFunctionTests { private final static String PARAM2 = "BAR"; private final static String VALID_URL = "maven://org.springframework.cloud.task.app:" - + "timestamp-task:jar:1.0.1.RELEASE"; + + "timestamp-task:jar:1.0.1.RELEASE"; - private final static String INVALID_URL = "maven://not.real.group:" - + "invalid:jar:1.0.0.BUILD-SNAPSHOT"; + private final static String INVALID_URL = "maven://not.real.group:" + "invalid:jar:1.0.0.BUILD-SNAPSHOT"; private final static String DEFAULT_STATUS = "test_status"; @@ -60,18 +59,16 @@ public class TaskLauncherFunctionTests { @Test public void testProcessorFromFunction() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration( - TaskLauncherSinkTestApplication.class)).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { + TestChannelBinderConfiguration.getCompleteConfiguration(TaskLauncherSinkTestApplication.class)) + .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false")) { InputDestination source = context.getBean(InputDestination.class); TaskLaunchRequest request = new TaskLaunchRequest(VALID_URL, Collections.emptyList(), - Collections.emptyMap(), null, "TESTAPP1"); + Collections.emptyMap(), null, "TESTAPP1"); GenericMessage message = new GenericMessage<>(request); source.send(message); TaskConfiguration.TestTaskLauncher target = context.getBean(TaskConfiguration.TestTaskLauncher.class); - assertThat(target.status(DEFAULT_STATUS).getState()) - .isEqualTo(LaunchState.complete); + assertThat(target.status(DEFAULT_STATUS).getState()).isEqualTo(LaunchState.complete); } } @@ -81,11 +78,10 @@ public class TaskLauncherFunctionTests { commandLineArgs.add(PARAM1); commandLineArgs.add(PARAM2); try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration( - TaskLauncherSinkTestApplication.class)).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, - commandLineArgs, null, context); + TestChannelBinderConfiguration.getCompleteConfiguration(TaskLauncherSinkTestApplication.class)) + .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false")) { + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, commandLineArgs, null, + context); verifySuccessWithParams(testTaskLauncher); testTaskLauncher = launchTaskByteArray(VALID_URL, commandLineArgs, null, context); @@ -99,11 +95,9 @@ public class TaskLauncherFunctionTests { @Test public void testSuccessWithAppName() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration( - TaskLauncherSinkTestApplication.class)).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, - null, APP_NAME, context); + TestChannelBinderConfiguration.getCompleteConfiguration(TaskLauncherSinkTestApplication.class)) + .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false")) { + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, null, APP_NAME, context); verifySuccessWithAppName(testTaskLauncher); testTaskLauncher = launchTaskByteArray(VALID_URL, null, APP_NAME, context); @@ -117,11 +111,10 @@ public class TaskLauncherFunctionTests { @Test public void testInvalidJar() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration( - TaskLauncherSinkTestApplication.class)).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskTaskLaunchRequest( - INVALID_URL, null, APP_NAME, context); + TestChannelBinderConfiguration.getCompleteConfiguration(TaskLauncherSinkTestApplication.class)) + .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false")) { + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskTaskLaunchRequest(INVALID_URL, null, + APP_NAME, context); verifySuccessWithAppName(testTaskLauncher); } } @@ -129,77 +122,62 @@ public class TaskLauncherFunctionTests { @Test public void testNoRun() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration( - TaskLauncherSinkTestApplication.class)).web(WebApplicationType.NONE).run( - "--spring.jmx.enabled=false")) { + TestChannelBinderConfiguration.getCompleteConfiguration(TaskLauncherSinkTestApplication.class)) + .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false")) { TaskConfiguration.TestTaskLauncher testTaskLauncher = context - .getBean(TaskConfiguration.TestTaskLauncher.class); - assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()) - .isEqualTo(LaunchState.unknown); + .getBean(TaskConfiguration.TestTaskLauncher.class); + assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()).isEqualTo(LaunchState.unknown); } } - private void verifySuccessWithAppName( - TaskConfiguration.TestTaskLauncher testTaskLauncher) { - assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()) - .isEqualTo(LaunchState.complete); + private void verifySuccessWithAppName(TaskConfiguration.TestTaskLauncher testTaskLauncher) { + assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()).isEqualTo(LaunchState.complete); assertThat(testTaskLauncher.getCommandlineArguments().size()).isEqualTo(0); assertThat(testTaskLauncher.getApplicationName()).isEqualTo(APP_NAME); } - private String getStringTaskLaunchRequest(String artifactURL, - List commandLineArgs, String applicationName) throws Exception { - TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, - this.properties, null, applicationName); + private String getStringTaskLaunchRequest(String artifactURL, List commandLineArgs, String applicationName) + throws Exception { + TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, this.properties, null, + applicationName); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(request); } - private void verifySuccessWithParams( - TaskConfiguration.TestTaskLauncher testTaskLauncher) { - assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()) - .isEqualTo(LaunchState.complete); + private void verifySuccessWithParams(TaskConfiguration.TestTaskLauncher testTaskLauncher) { + assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()).isEqualTo(LaunchState.complete); assertThat(testTaskLauncher.getCommandlineArguments().size()).isEqualTo(2); assertThat(testTaskLauncher.getCommandlineArguments().get(0)).isEqualTo(PARAM1); assertThat(testTaskLauncher.getCommandlineArguments().get(1)).isEqualTo(PARAM2); - assertThat(testTaskLauncher.getApplicationName().startsWith(TASK_NAME_PREFIX)) - .isTrue(); + assertThat(testTaskLauncher.getApplicationName().startsWith(TASK_NAME_PREFIX)).isTrue(); } - private TaskConfiguration.TestTaskLauncher launchTaskString(String artifactURL, - List commandLineArgs, String applicationName, - ConfigurableApplicationContext context) throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = context - .getBean(TaskConfiguration.TestTaskLauncher.class); - String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, - applicationName); + private TaskConfiguration.TestTaskLauncher launchTaskString(String artifactURL, List commandLineArgs, + String applicationName, ConfigurableApplicationContext context) throws Exception { + TaskConfiguration.TestTaskLauncher testTaskLauncher = context.getBean(TaskConfiguration.TestTaskLauncher.class); + String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, applicationName); GenericMessage message = new GenericMessage<>(stringRequest); InputDestination source = context.getBean(InputDestination.class); source.send(message); return testTaskLauncher; } - private TaskConfiguration.TestTaskLauncher launchTaskByteArray(String artifactURL, - List commandLineArgs, String applicationName, - ConfigurableApplicationContext context) throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = context - .getBean(TaskConfiguration.TestTaskLauncher.class); - String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, - applicationName); + private TaskConfiguration.TestTaskLauncher launchTaskByteArray(String artifactURL, List commandLineArgs, + String applicationName, ConfigurableApplicationContext context) throws Exception { + TaskConfiguration.TestTaskLauncher testTaskLauncher = context.getBean(TaskConfiguration.TestTaskLauncher.class); + String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, applicationName); GenericMessage message = new GenericMessage<>(stringRequest.getBytes()); InputDestination source = context.getBean(InputDestination.class); source.send(message); return testTaskLauncher; } - private TaskConfiguration.TestTaskLauncher launchTaskTaskLaunchRequest( - String artifactURL, List commandLineArgs, String applicationName, - ConfigurableApplicationContext context) - throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = context - .getBean(TaskConfiguration.TestTaskLauncher.class); - TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, - this.properties, null, applicationName); + private TaskConfiguration.TestTaskLauncher launchTaskTaskLaunchRequest(String artifactURL, + List commandLineArgs, String applicationName, ConfigurableApplicationContext context) + throws Exception { + TaskConfiguration.TestTaskLauncher testTaskLauncher = context.getBean(TaskConfiguration.TestTaskLauncher.class); + TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, this.properties, null, + applicationName); GenericMessage message = new GenericMessage<>(request); InputDestination source = context.getBean(InputDestination.class); source.send(message); @@ -207,7 +185,9 @@ public class TaskLauncherFunctionTests { } @SpringBootApplication - @Import({TaskLauncherSink.class}) + @Import({ TaskLauncherSink.class }) public static class TaskLauncherSinkTestApplication { + } + } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java index bcbd180e..f3e2b99f 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/listener/TaskEventTests.java @@ -37,15 +37,15 @@ public class TaskEventTests { @Test public void testDefaultConfiguration() { ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder() - .sources(TestChannelBinderConfiguration - .getCompleteConfiguration(TaskEventsApplication.class)).web(WebApplicationType.NONE).build() - .run(); + .sources(TestChannelBinderConfiguration.getCompleteConfiguration(TaskEventsApplication.class)) + .web(WebApplicationType.NONE).build().run(); assertThat(applicationContext.getBean("taskEventEmitter")).isNotNull(); } @EnableTask @SpringBootApplication public static class TaskEventsApplication { + } }